开发者

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

For example, system("sh /mydir/some-script.sh &")开发者_如何学Go


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜