UNIX 进程:fork() 和 wait()
这是我对 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确地理解了这个问题,你想要这样的东西:
main
调用function
function
调用fork
to创建 child/ren,并在父进程中返回main
稍后在 child/ren 上调用wait
这很好......名义上,您不必 /em> 将子进程的 PID 传回给
main
,因为您只需调用wait
即可获取恰好存在的任何子进程;但是,要使用waitid
或waitpid
,您需要/想要将它们提供给main
。您可以将 PID 返回到像链接列表或 NULL 终止数组这样的结构中的main
,或者创建某种文件范围或全局变量来包含该列表。Linux 手册页中有关于
wait(2)
的详细说明(man 2 wait
左右)If I follow the question correctly, you want to have something like this:
main
callsfunction
function
callsfork
to create child/ren, and returns in the parent processmain
later callswait
on the child/renThis is fine… Nominally, you don't have to pass the child(ren)'s PID(s) back to
main
, because you can just callwait
to reap any child process that happens to exist; however, to usewaitid
orwaitpid
, you would need/want to provide them back up tomain
. You could either return the PID tomain
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)是的,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.