编写一个c程序,满足以下要求: 用系统调用列出所有的信号;(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-06 16:44:50 浏览: 40
以下是满足要求的C程序:
```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() {
int pid1, pid2;
pid1 = fork(); // 创建子进程1
if (pid1 < 0) {
printf("Error: fork failed.\n");
exit(1);
} else if (pid1 == 0) { // 子进程1
signal(SIGINT, SIG_IGN); // 忽略中断信号
while (1) {
printf("Child Process 1 is running...\n");
sleep(1);
}
} else { // 父进程
pid2 = fork(); // 创建子进程2
if (pid2 < 0) {
printf("Error: fork failed.\n");
exit(1);
} else if (pid2 == 0) { // 子进程2
signal(SIGINT, SIG_IGN); // 忽略中断信号
while (1) {
printf("Child Process 2 is running...\n");
sleep(1);
}
} else { // 父进程
printf("Parent Process is running...\n");
signal(SIGINT, SIG_DFL); // 捕捉中断信号
while (1) {
sleep(1);
}
}
}
return 0;
}
```
运行程序后,父进程会等待两个子进程终止。当父进程捕捉到中断信号(Ctrl-C)时,会向两个子进程发出信号,子进程会捕捉到信号并输出相应的信息后终止。当两个子进程都终止后,父进程输出相应的信息后也终止。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)