简体   繁体   English

在 C 语言的 Linux 编程中,子进程可以等待父进程终止吗?

[英]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.

相关问题 子进程等待父级,然后执行,反之亦然 - Child Process wait parent then it execute and then vice-versa in C linux 在C语言中,如果父进程终止,那么子进程会自动终止吗? - In C, if a parent process terminates, then will the child process automatically terminate? 当父进程等待子进程终止时,子进程如何杀死父进程? - How can child kill parent process while parent process waits until child process to terminate? 父进程不等待子进程(C代码) - parent process does not wait for the child process (c code) 等待子进程是否终止-C - Waiting for child process to terminate, or not - C 子进程中的Execl()和父进程中的wait() - Execl() in a child process and wait() in the parent process C Linux编程-管道使子进程退出 - C Linux programming - Pipe makes child process exit C linux中子进程与父进程之间的通信:父进程未阻塞 - communication between child and parent processes in C linux: parent process not blocking 使用 `clone()` 创建子进程。 为什么 `wait()` 不等待它终止? - Created child process with `clone()`. Why does `wait()` not wait for it to terminate? linux - 由子进程中断的父进程的sleep() - linux - sleep() of parent process interrupted by child process
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM