[英]Can a child process wait for the parent process to terminate in Linux programming in C?
在Linux的C编程中,我知道wait()
函数用于等待子进程终止,但是子进程是否有一些方法(或函数)可以等待父进程终止?
Linux has an extension (as in, non-POSIX functions) for this. Linux 对此有一个扩展(如非 POSIX 函数)。 Look up
prctl
("process-related control").查找
prctl
(“进程相关控制”)。
With prctl
, you can arrange for the child to get a signal when the parent dies.使用
prctl
,您可以安排孩子在父母去世时收到信号。 Look for the PR_SET_PDEATHSIG
operation code used with prctl
.查找与
prctl
使用的PR_SET_PDEATHSIG
操作代码。
For instance, if you set it to the SIGKILL
signal, it effectively gives us a way to have the children die when a parent dies.例如,如果您将其设置为
SIGKILL
信号,则它有效地为我们提供了一种在父母死亡时让孩子死亡的方法。 But of course, the signal can be something that the child can catch.但当然,信号可以是孩子可以捕捉到的东西。
prctl
can do all kinds of other things. prctl
可以做各种其他的事情。 It's like an ioctl
whose target is the process itself: a "process ioctl".它就像一个
ioctl
其目标是进程本身:“进程 ioctl”。
Short answer: no.简短的回答:没有。
A parent process can control the terminal or process group of its children, which is why we have the wait()
and waitpid()
functions.父进程可以控制其子进程的终端或进程组,这就是我们拥有
wait()
和waitpid()
函数的原因。 A child doesn't have that kind of control over its parent, so there's nothing built in for that.孩子对其父母没有那种控制权,因此没有任何内置的东西。
If you really need a child to know when its parent exits, you can have the parent send a signal to the child in an atexit()
handler, and have the child catch that signal.如果您真的需要孩子知道其父级何时退出,您可以让父级在
atexit()
处理程序中向子级发送信号,并让子级捕获该信号。
In Linux, you can use prctl with the value PR_SET_PDEATHSIG to establish a signal that will be sent to your process when the thread that created it dies.在 Linux 中,您可以使用值为 PR_SET_PDEATHSIG 的 prctl 来建立一个信号,当创建它的线程死亡时,该信号将发送到您的进程。 Maybe you find it useful.
也许你觉得它很有用。
当父进程结束时,子进程被init采用,因此如果ppid()==1或ppid()!=就足以检查子进程,而不是原始的PPID,这意味着父进程已完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.