对异步 shell 命令的 POSIX system(3) 调用会立即返回吗?

发布于 2024-11-02 02:16:30 字数 63 浏览 1 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

动次打次papapa 2024-11-09 02:16:30
system("sh /mydir/some-script.sh &")

执行

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

system 将在外壳返回后立即返回,这将在启动内壳后立即返回。这两个 shell 都不会等待 some-script.sh 完成。

$ cat some-script.sh
sleep 1
echo foo

$ /bin/sh -c 'sh some-script.sh &' ; echo bar ; sleep 2
bar
foo
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
感性 2024-11-09 02:16:30

是的,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, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文