简体   繁体   English

如何无害地杀死子进程

[英]How to kill child process harmlessly

Parent process forks and gets child id.父进程派生并获取子 ID。 Child do some stuff.孩子做一些事情。 If it doesn't finish after 1 second parent kills it by id.如果它在 1 秒后没有完成,则父母会通过 id 杀死它。 But what if child has finished before 1 second elapsed and system executes another process with same id as my child had.但是,如果孩子在 1 秒之前完成并且系统执行另一个与我孩子具有相同 ID 的进程,该怎么办。 In this case parent will kill innocent process.在这种情况下,父进程将杀死无辜的进程。 How can I avoid this?我怎样才能避免这种情况?

The PID is reserved until wait (or a similar function like waitpid ) tells the parent that the process has exited. PID 被保留,直到wait (或类似的函数,如waitpid )告诉父进程已退出。

If the process has exited but you the parent hasn't been told by wait yet, the process is called a "zombie".如果进程已经退出,但你的父进程还没有被wait告知,这个进程被称为“僵尸”。 Nothing happens when you kill a zombie process . 杀死僵尸进程时什么也不会发生

So, your parent just needs to be careful to not send any signals after wait tells it that the child process finished.因此,您的父进程只需要小心不要在wait告诉它子进程完成后发送任何信号。 This should be easy.这应该很容易。 There is no race condition involved.不涉及竞争条件。

Note: This also means that you need to call wait (or a related function like waitpid ) after spawning a child process.注意:这也意味着您需要在生成子进程后调用wait (或类似waitpid的相关函数)。 Alternatively, if your process exits, then zombie processes it created disappear (because they get "adopted" by PID 1, which calls wait ).或者,如果您的进程退出,那么它创建的僵尸进程就会消失(因为它们被调用wait的 PID 1“采用”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM