生出一个独立的孩子
如何使用 C 生成一个独立的子进程来处理其业务而不考虑父进程?
我想生成几个进程,在它们创建后不久,它们会在完成工作之前休眠大约 2 分钟。
但是,我不希望父亲等到孩子完成,因为与此同时我想产生更多进程。
我在Linux上。
How can you use C to spawn an independent child process that goes about its business without thinking about the father?
I want to spawn several processes and shortly after they have been created they go to sleep for about 2 minutes before they do their job.
However, I don't want the father to wait until the child is finished because in the meantime I want to spawn off more processes.
I'm on Linux.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 fork()。
fork() 系统调用
Use fork().
The fork() System Call
只需使用
fork(2)
生成所需数量的进程,然后在父进程中调用exit()
即可。孤儿将被init
进程收养。Simply spawn as many processes as you need using
fork(2)
, then callexit()
in the parent process. The orphaned children will be adopted by theinit
process.如果您想要创建多个子进程,在创建后立即执行其“自己的业务”,则应该使用 vfork()(用于创建新进程而不完全复制父进程的地址空间)和
exec()
系列,用您想要的任何内容替换子进程的图像。如果您不希望父亲等待孩子完成,则应该利用异步信号处理。当子进程结束时会发送 SIGCHLD。因此,您可以将
wait()
放在 SIGCHLD 的信号处理程序中而不是父进程中,并让信号处理程序收集子进程的返回状态。下面是一个玩具示例:
If what you want is creating multiple child processes doing their "own business" right after their creation, you should use
vfork()
(used to create new processes without fully copying the address space of the father process) andexec()
family to replace the children processes' images with whatever you want.if you don't want the father to wait until the child is finished, you should take advantage of asynchronous signal handling. A SIGCHLD is sent when a child process ends. So you can put the
wait()
within the signal handler for SIGCHLD rather than the father process and let the signal handler collect returning status for child process.Below is a toy example: