1.编写一段程序,使用系统调用fork()创建两个子进程,再用系统 调用signal()让父进程捕捉组合键的中断信号(即按ctrl+c键),当 捕捉到中断信号后,父进程用系统调用kill()向两个子进程发出信号, 子进程捕捉到父进程发来的信号后,分别输出下列信息后终止: Child process 1 is killed by parent! Child process 2 is killed by parent! 父进程等待两个子进程终止后,输出以下信息后终止: Parent process exit!
时间: 2024-02-17 14:03:08 浏览: 21
好的,以下是实现上述功能的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void child_process_1();
void child_process_2();
void signal_handler(int signal);
int main() {
pid_t pid1, pid2;
int status;
// 创建子进程1
pid1 = fork();
if (pid1 < 0) {
perror("fork 1 failed");
exit(EXIT_FAILURE);
} else if (pid1 == 0) {
child_process_1();
exit(EXIT_SUCCESS);
}
// 创建子进程2
pid2 = fork();
if (pid2 < 0) {
perror("fork 2 failed");
exit(EXIT_FAILURE);
} else if (pid2 == 0) {
child_process_2();
exit(EXIT_SUCCESS);
}
// 等待父进程捕捉中断信号
signal(SIGINT, signal_handler);
printf("Parent process is running. Press CTRL+C to terminate child processes.\n");
// 等待两个子进程终止
waitpid(pid1, &status, 0);
waitpid(pid2, &status, 0);
printf("Parent process exit!\n");
exit(EXIT_SUCCESS);
}
void child_process_1() {
printf("Child process 1 is running.\n");
sleep(10);
printf("Child process 1 is killed by parent!\n");
}
void child_process_2() {
printf("Child process 2 is running.\n");
sleep(10);
printf("Child process 2 is killed by parent!\n");
}
void signal_handler(int signal) {
if (signal == SIGINT) {
printf("CTRL+C is pressed. Killing child processes...\n");
kill(0, SIGKILL);
exit(EXIT_SUCCESS);
}
}
```
该程序通过调用 `fork()` 系统调用创建了两个子进程,并在父进程中注册了一个中断信号处理函数 `signal_handler()`,用于捕捉用户按下 CTRL+C 的中断信号。
当父进程捕捉到中断信号后,会向两个子进程发送信号 `SIGKILL`,子进程在收到该信号后会输出相应的信息并终止。
当两个子进程都终止后,父进程会输出相应的信息并终止。