用系统调用列出所有的信号;(kill –l) 用系统调用signal()让父进程捕捉键盘上来的中断信号(Ctrl-C); 当捕捉到中断信号后,父进程用系统调用kill()向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止 Child Process 1 is Killed by Parent! Child Process 2 is Killed by Parent! 父进程等待两个子进程终止后,输出如下的信息后终止: Parent Process is Killed!
时间: 2024-02-12 22:06:25 浏览: 21
下面是一个示例程序,实现了上述功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void child1_handler(int sig) {
printf("Child Process 1 is Killed by Parent!\n");
exit(0);
}
void child2_handler(int sig) {
printf("Child Process 2 is Killed by Parent!\n");
exit(0);
}
int main() {
pid_t pid1, pid2;
signal(SIGINT, SIG_IGN); // 忽略 Ctrl+C 中断信号
signal(SIGTERM, SIG_DFL); // 恢复默认的终止信号处理程序
// 创建子进程1
pid1 = fork();
if (pid1 < 0) {
perror("fork");
exit(1);
} else if (pid1 == 0) { // 子进程1
signal(SIGTERM, child1_handler); // 设置信号处理函数
while (1) {
printf("Child Process 1 is running...\n");
sleep(1);
}
} else { // 父进程
// 创建子进程2
pid2 = fork();
if (pid2 < 0) {
perror("fork");
exit(1);
} else if (pid2 == 0) { // 子进程2
signal(SIGTERM, child2_handler); // 设置信号处理函数
while (1) {
printf("Child Process 2 is running...\n");
sleep(1);
}
} else { // 父进程
// 等待键盘中断信号
while (1) {
if (getchar() == '\n') {
break;
}
}
// 向子进程发送 SIGTERM 信号
kill(pid1, SIGTERM);
kill(pid2, SIGTERM);
// 等待子进程退出
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
printf("Parent Process is Killed!\n");
exit(0);
}
}
}
```
该程序使用了 `signal()` 系统调用来设置信号处理函数。在父进程中,忽略了 Ctrl+C 中断信号;在子进程中,分别设置了捕捉到 SIGTERM 信号后的处理函数。在父进程中,使用了 `getchar()` 等待用户键入回车,表示捕捉到了中断信号,并使用 `kill()` 向两个子进程发送 SIGTERM 信号。在两个子进程都退出后,父进程输出相应的信息并退出。