对异步 shell 命令的 POSIX system(3) 调用会立即返回吗?
例如,system("sh /mydir/some-script.sh &")
For example, system("sh /mydir/some-script.sh &")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
例如,system("sh /mydir/some-script.sh &")
For example, system("sh /mydir/some-script.sh &")
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(2)
执行
system
将在外壳返回后立即返回,这将在启动内壳后立即返回。这两个 shell 都不会等待some-script.sh
完成。executes
system
will return as soon as outer shell returns, which will be immediately after it launches the inner shell. Neither shell will wait forsome-script.sh
to finish.是的,shell 会分叉脚本并立即返回,但是您没有一种简单的方法来了解脚本如何结束以及是否结束。
运行此类异步命令的“正确”方法是
fork(2)
您的进程,在子进程中调用execve(2)
,并将二进制文件设置为>/bin/sh
并将参数之一设置为脚本的名称,并使用带有的
waitpid(2)
系统调用定期从父级轮询子级WNOHANG 选项。当waitpid
返回 -1 时,您知道脚本已结束,您可以获取其返回代码。事实上,
system(3)
的作用几乎相同,唯一的例外是对waitpid
的调用会阻塞,直到进程终止。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, callexecve(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 thewaitpid(2)
system call with theWNOHANG
option. Whenwaitpid
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 towaitpid
blocks until the process terminates.