软中断通信 使用系统调用fork( )创建2个子进程p1和p2,在父进程中使用系统调用signal( )捕捉来自键盘上的软中断信号SIGINT(即按Ctrl-C),当捕捉到软中断信号SIGINT后,父进程使用系统调用kill( )分别向2个子进程发出软中断信号SIGUSR1和SIGUSR2,子进程捕捉到信号后分别输出信息“Child process p1 is killed by parent!”和“Child process p2 is killed by parent!”后终止。而父进程等待2个子进程终止后,输出信息“Parent process is killed!”后终止。
时间: 2023-06-24 20:03:57 浏览: 159
这个问题需要编写一个程序来实现,以下是一个可能的解决方案:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void handle_sigint(int sig) {
// 在父进程中接收到 SIGINT 信号后向子进程发送信号
if (sig == SIGINT) {
printf("Received SIGINT, sending SIGUSR1 to p1 and SIGUSR2 to p2.\n");
kill(p1, SIGUSR1);
kill(p2, SIGUSR2);
}
}
void handle_sigusr1(int sig) {
// 在子进程 p1 中接收到 SIGUSR1 信号后输出信息并终止
if (sig == SIGUSR1) {
printf("Child process p1 is killed by parent!\n");
exit(0);
}
}
void handle_sigusr2(int sig) {
// 在子进程 p2 中接收到 SIGUSR2 信号后输出信息并终止
if (sig == SIGUSR2) {
printf("Child process p2 is killed by parent!\n");
exit(0);
}
}
int main() {
pid_t p1, p2;
// 创建子进程 p1 和 p2
p1 = fork();
if (p1 < 0) {
fprintf(stderr, "Failed to fork p1.\n");
return 1;
} else if (p1 == 0) {
// 在子进程 p1 中注册 SIGUSR1 信号处理函数
signal(SIGUSR1, handle_sigusr1);
while (1) {
// 子进程 p1 不断循环等待信号
}
} else {
// 在父进程中继续创建子进程 p2
p2 = fork();
if (p2 < 0) {
fprintf(stderr, "Failed to fork p2.\n");
return 1;
} else if (p2 == 0) {
// 在子进程 p2 中注册 SIGUSR2 信号处理函数
signal(SIGUSR2, handle_sigusr2);
while (1) {
// 子进程 p2 不断循环等待信号
}
} else {
// 在父进程中注册 SIGINT 信号处理函数
signal(SIGINT, handle_sigint);
// 等待子进程 p1 和 p2 终止
waitpid(p1, NULL, 0);
waitpid(p2, NULL, 0);
printf("Parent process is killed!\n");
exit(0);
}
}
return 0;
}
```
这个程序首先使用 `fork()` 创建了两个子进程 p1 和 p2,然后在父进程中注册了 SIGINT 信号处理函数 `handle_sigint()`。当父进程接收到 SIGINT 信号后,会调用 `handle_sigint()` 函数向子进程 p1 和 p2 分别发送 SIGUSR1 和 SIGUSR2 信号。在子进程 p1 和 p2 中分别注册了 SIGUSR1 和 SIGUSR2 信号处理函数,当它们接收到信号后会输出相应的信息并调用 `exit(0)` 终止进程。在父进程中使用 `waitpid()` 等待两个子进程终止,然后输出信息并终止进程。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)