使用系统调用 fork0创造二个进程,父进程睡眠 2 秒后,用系统调用Kill() 向两个子进程发出信号,子进程捕捉到信息后分别输出下列信息终止: Child Processl1 is Killed by Parent! Child Processl2 is Killed by Parent! 父进程等待两个子进程终止后,输出如下的信息后终止: Parent Process is Killed !写出c语言程序
时间: 2024-02-21 22:01:56 浏览: 69
下面是一个可能的C语言程序实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
void child_handler(int sig) {
if (sig == SIGTERM) {
printf("Child Process1 is Killed by Parent!\n");
exit(0);
}
}
void child_handler2(int sig) {
if (sig == SIGTERM) {
printf("Child Process2 is Killed by Parent!\n");
exit(0);
}
}
int main() {
pid_t pid1, pid2;
pid1 = fork();
if (pid1 == 0) {
signal(SIGTERM, child_handler);
while(1) {
sleep(1);
}
}
pid2 = fork();
if (pid2 == 0) {
signal(SIGTERM, child_handler2);
while(1) {
sleep(1);
}
}
// 父进程等待2秒后,向两个子进程发送SIGTERM信号
sleep(2);
kill(pid1, SIGTERM);
kill(pid2, SIGTERM);
// 父进程等待两个子进程终止后,输出信息后终止
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
printf("Parent Process is Killed!\n");
return 0;
}
```
阅读全文