UNIX 进程:fork() 和 wait()

发布于 2024-12-27 01:26:59 字数 413 浏览 4 评论 0原文

这是我对 fork() 和将要发生的相应 wait() 的问题:

在我的 main() 中,我调用一个函数,假设 function() 使用 fork() 系统调用,但我希望 function() 返回而不等待子进程终止,因此 main() 必须在它们之前等待终止。

那么,main()是否可以对已在另一个函数体内fork()ed的子函数调用wait()调用我的这个main()

如果是,我是否必须通过变量将子进程的 pid 传递给 main()

this is my question on fork() and the respective wait() that will take place:

In my main(), I call a function, let's say function() that uses the fork() system call, but I want function() to return without waiting for the children to terminate, and thus main() has to wait for them before terminating.

So, is it possible for main() to call wait() on children that have been fork()ed in the body of another function called my this main()?

If yes, do I have to pass the children's pid's to main() through a variable?

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

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

发布评论

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

评论(2

夏了南城 2025-01-03 01:26:59

如果我正确地理解了这个问题,你想要这样的东西:

  • main 调用 function
  • function 调用 fork to创建 child/ren,并在父进程中返回
  • main 稍后在 child/ren 上调用 wait

这很好......名义上,您不必 /em> 将子进程的 PID 传回给main,因为您只需调用 wait 即可获取恰好存在的任何子进程;但是,要使用 waitidwaitpid,您需要/想要将它们提供给 main。您可以将 PID 返回到像链接列表或 NULL 终止数组这样的结构中的 main,或者创建某种文件范围或全局变量来包含该列表。

Linux 手册页中有关于 wait(2) 的详细说明(man 2 wait 左右)

If I follow the question correctly, you want to have something like this:

  • main calls function
  • function calls fork to create child/ren, and returns in the parent process
  • main later calls wait on the child/ren

This is fine… Nominally, you don't have to pass the child(ren)'s PID(s) back to main, because you can just call wait to reap any child process that happens to exist; however, to use waitid or waitpid, you would need/want to provide them back up to main. You could either return the PID to main in a structure like a linked list or NULL-terminated array, or create some kind of file-scoped or global variable to contain the list.

There's a pretty good breakdown in the Linux manual page for wait(2) (man 2 wait or so)

辞取 2025-01-03 01:26:59

是的,main 可以等待分叉子函数的子函数。 wait() 等待任何子进程终止。

您仍然希望将 fork() 的返回值传递给主函数,因为您需要它来决定您是子进程还是父进程。

Yes, main can wait for children which forked in sub-functions. wait () waits for any child to terminate.

You will still want to pass the return value of fork() to the main function, because you will need it to decide whether you are the child or the parent process.

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