Will POSIX system(3) call to an asynchronous shell command return immediately?

别说谁变了你拦得住时间么 提交于 2019-12-13 02:42:35

问题


For example, system("sh /mydir/some-script.sh &")


回答1:


system("sh /mydir/some-script.sh &")

executes

/bin/sh -c 'sh /mydir/some-script.sh &'

system will return as soon as outer shell returns, which will be immediately after it launches the inner shell. Neither shell will wait for some-script.sh to finish.

$ cat some-script.sh
sleep 1
echo foo

$ /bin/sh -c 'sh some-script.sh &' ; echo bar ; sleep 2
bar
foo



回答2:


Yes, the shell will fork the script and return immediately, but you don't have an easy way of knowing how and whether the script has ended.

The "proper" way to run such an asynchronous command would be to fork(2) your process, call execve(2) in the child with the binary set to /bin/sh and one of the arguments set to the name of your script, and poll the child periodically from the parent using the waitpid(2) system call with the WNOHANG option. When waitpid returns -1, you know that the script has ended and you can fetch its return code.

In fact, what system(3) does is almost the same with the only exception that the call to waitpid blocks until the process terminates.



来源:https://stackoverflow.com/questions/5666962/will-posix-system3-call-to-an-asynchronous-shell-command-return-immediately

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!