用系统调用列出所有的信号;(kill –l) 用系统调用signal()让父进程捕捉键盘上来的中断信号(Ctrl-C); 当捕捉到中断信号后,父进程用系统调用kill()向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止 Child Process 1 is Killed by Parent! Child Process 2 is Killed by Parent! 父进程等待两个子进程终止后,输出如下的信息后终止: Parent Process is Killed!
时间: 2023-12-03 08:46:28 浏览: 33
以下是一个示例代码实现:
```c
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
void child_process_1(int sig) {
printf("Child Process 1 is Killed by Parent!\n");
exit(0);
}
void child_process_2(int sig) {
printf("Child Process 2 is Killed by Parent!\n");
exit(0);
}
int main() {
pid_t pid1, pid2;
int status;
// 创建子进程1
if ((pid1 = fork()) < 0) {
perror("fork error");
exit(1);
} else if (pid1 == 0) { // 子进程1
signal(SIGINT, SIG_IGN); // 子进程1忽略中断信号
while(1) {
// 子进程1不断循环
}
} else { // 父进程
// 创建子进程2
if ((pid2 = fork()) < 0) {
perror("fork error");
exit(1);
} else if (pid2 == 0) { // 子进程2
signal(SIGINT, SIG_IGN); // 子进程2忽略中断信号
while(1) {
// 子进程2不断循环
}
} else { // 父进程
signal(SIGINT, child_process_1); // 父进程捕捉中断信号,执行child_process_1函数
waitpid(pid1, &status, 0); // 等待子进程1终止
signal(SIGINT, child_process_2); // 父进程捕捉中断信号,执行child_process_2函数
waitpid(pid2, &status, 0); // 等待子进程2终止
printf("Parent Process is Killed!\n");
}
}
return 0;
}
```
该程序创建了两个子进程,分别忽略中断信号。父进程捕捉到中断信号后,分别向两个子进程发送信号,子进程捕捉到信号后输出信息并终止。最后父进程等待两个子进程的终止,并输出一条信息后终止。