C语言 如何杀死叉子的孩子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13273836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to kill child of fork?
提问by MOHAMED
I have the following code which create a child fork. And I want to kill the child before it finish its execution in the parent. how to do it?
我有以下代码可以创建一个子叉。我想在孩子在父母中完成执行之前杀死它。怎么做?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int i;
main (int ac, char **av)
{
int pid;
i = 1;
if ((pid = fork()) == 0) {
/* child */
while (1) {
printf ("I m child\n");
sleep (1);
}
}
else {
/* Error */
perror ("fork");
exit (1);
}
sleep (10)
// TODO here: how to add code to kill child??
}
采纳答案by md5
Send a signal.
发送信号。
#include <sys/types.h>
#include <signal.h>
kill(pid, SIGKILL);
/* or */
kill(pid, SIGTERM);
The second form preferable, among other, if you'll handle signals by yourself.
如果您要自己处理信号,则最好使用第二种形式。
回答by Ed Heal
See killsystem call. Usually a good idea to use SIGTERM first to give the process an opportunity to die gratefully before using SIGKILL.
请参阅杀死系统调用。在使用 SIGKILL 之前,首先使用 SIGTERM 给进程一个机会感激地死去通常是个好主意。
EDIT
编辑
Forgot you need to use waitpidto get the return status of that process and prevent zombie processes.
忘了您需要使用waitpid来获取该进程的返回状态并防止僵尸进程。
A FURTHER EDIT
进一步编辑
You can use the following code:
您可以使用以下代码:
kill(pid, SIGTERM);
bool died = false;
for (int loop; !died && loop < 5 /*For example */; ++loop)
{
int status;
pid_t id;
sleep(1);
if (waitpid(pid, &status, WNOHANG) == pid) died = true;
}
if (!died) kill(pid, SIGKILL);
It will give the process 5 seconds to die gracefully
它将给进程 5 秒钟的时间优雅地死去
回答by alk
Issue kill(pid, SIGKILL)from out of the parent.
发出kill(pid, SIGKILL)从走出父。

