我有以下代码,它创建一个子进程。我想在父进程中让子进程在完成执行之前被终止。怎么做?
#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??
}
fork()
函数返回的是pid_t
类型而不是int
类型,因此你应该声明与之对应的变量类型。 - Niklas B.