Will POSIX system(3) call to an asynchrono

2019-09-11 02:33发布

问题:

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.