2.20 kill、raise、abort函数

子进程先执行还是父进程先执行不确定,他们抢占系统资源。
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if(pid == 0) {
// 子进程
int i = 0;
for(i = 0; i < 5; i++) {
printf("child process\n");
sleep(1);
}
} else if(pid > 0) {
// 父进程
printf("parent process\n");
sleep(2);
printf("kill child process now\n");
kill(pid, SIGINT);//终止进程,pid为子进程的进程号
}
return 0;
}
执行结果如下:

该程序展示了在C语言中如何使用fork创建子进程,然后父进程通过kill函数发送SIGINT信号来终止子进程。子进程在被杀之前打印childprocess,每秒一次,而父进程在等待两秒后发出杀死子进程的指令。
1313

被折叠的 条评论
为什么被折叠?



