编制一段程序,使用系统调用fork()创建两个子进程,再用系统调用signal()让父进程捕捉键盘上来的中断信号(即按ctrl+c键),当捕捉到中断信号后,父进程用系统调用kill()向两个子进程发出信号,子进程捕捉到信号后,分别输出下列信息后终止: child process1 is killed by parent! child process2 is killed by parent! 父进程等待两个子进程终止后,输出以下信息后终止: parent process is killed!
时间: 2024-02-21 16:02:22 浏览: 101
以下是示例代码:
```c
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
void child_process1();
void child_process2();
void signal_handler(int signum);
int main() {
pid_t pid1, pid2;
signal(SIGINT, signal_handler);
pid1 = fork();
if (pid1 < 0) {
printf("Error: Failed to fork child process 1.\n");
exit(1);
} else if (pid1 == 0) {
child_process1();
}
pid2 = fork();
if (pid2 < 0) {
printf("Error: Failed to fork child process 2.\n");
exit(1);
} else if (pid2 == 0) {
child_process2();
}
// 等待子进程终止
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
printf("parent process is killed!\n");
return 0;
}
void child_process1() {
while (1) {
printf("child process1 is running...\n");
sleep(1);
}
}
void child_process2() {
while (1) {
printf("child process2 is running...\n");
sleep(1);
}
}
void signal_handler(int signum) {
printf("Received signal %d, killing child processes...\n", signum);
kill(0, SIGTERM);
exit(0);
}
```
在上面的代码中,我们在主函数中使用 `fork()` 系统调用创建了两个子进程,并使用 `signal()` 系统调用让父进程捕捉键盘上来的中断信号 `SIGINT`。当捕捉到中断信号后,父进程使用 `kill()` 向两个子进程发出信号 `SIGTERM`,子进程捕捉到信号后,分别输出指定的信息并终止。父进程等待两个子进程终止后,输出指定的信息并终止。
阅读全文