编制一段程序,使用系统调用fork()创建两个子进程,再用系统调用signal()让父进程捕捉键盘上来的中断信号(即按ctrl+c键),当捕捉到中断信号后,父进程用系统调用kill()向两个子进程发出信号,子进程捕捉到信号后,分别输出下列信息后终止: child process1 is killed by parent! child process2 is killed by parent! 父进程等待两个子进程终止后,输出以下信息后终止: parent process is killed!
时间: 2023-06-19 08:03:42 浏览: 91
下面是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
void child_handler1(int signum) {
printf("child process1 is killed by parent!\n");
exit(0);
}
void child_handler2(int signum) {
printf("child process2 is killed by parent!\n");
exit(0);
}
int main() {
pid_t pid1, pid2;
int status1, status2;
pid1 = fork();
if (pid1 < 0) {
perror("fork");
exit(1);
} else if (pid1 == 0) {
// child process 1
signal(SIGINT, child_handler1);
while (1) {
printf("child process1 is running...\n");
sleep(1);
}
} else {
pid2 = fork();
if (pid2 < 0) {
perror("fork");
exit(1);
} else if (pid2 == 0) {
// child process 2
signal(SIGINT, child_handler2);
while (1) {
printf("child process2 is running...\n");
sleep(1);
}
} else {
// parent process
signal(SIGINT, SIG_IGN); // ignore SIGINT
printf("Press Ctrl+C to terminate...\n");
while (1) {
sleep(1);
}
}
}
// wait for child processes to terminate
waitpid(pid1, &status1, 0);
waitpid(pid2, &status2, 0);
printf("parent process is killed!\n");
return 0;
}
```
程序首先创建两个子进程并分别给它们注册捕捉中断信号的处理函数。父进程则忽略中断信号,并进入一个死循环等待用户按下 Ctrl+C 键。
当捕捉到中断信号后,父进程会向两个子进程发送 SIGTERM 信号,子进程接收到信号后会输出相应的信息并调用 exit() 函数终止进程。父进程在等待两个子进程终止后,输出相应信息并调用 exit() 函数终止进程。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)