我有下面的代碼創建一個子分叉。我想在孩子完成父母的執行之前殺死孩子。怎麼做?如何殺死叉子?
#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??
}
'叉()'返回一個'pid_t' ,而不是'int',所以你應該聲明你的變量是這樣的。 –
與原始問題無關:當fork返回一個新進程時(在成功的情況下),父進程和子進程都從調用fork的地方繼續執行。對於父進程,子進程的pid = 0(嗯,它總是可以通過getpid()獲得)並且pid> 0。該錯誤僅在fork返回-1時出現。在你的代碼中,你將一個「父進程」部分視爲一個錯誤。 –
[如何殺死父進程的子進程?](http://stackoverflow.com/questions/6501522/how-to-kill-a-child-process-by-the-parent-process) – goozez