编写一个c程序,满足以下要求: 用系统调用列出所有的信号;(kill –l) 用系统调用signal()让父进程捕捉键盘上来的中断信号(Ctrl-C); 当捕捉到中断信号后,父进程用系统调用kill()向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止 Child Process 1 is Killed by Parent! Child Process 2 is Killed by Parent! 父进程等待两个子进程终止后,输出如下的信息后终止: Parent Process is Killed!
时间: 2024-02-11 15:07:22 浏览: 11
以下是符合要求的c程序代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
void sigint_handler(int signo);
int main()
{
pid_t pid1, pid2;
int status;
int signum;
//列出所有信号
printf("All signals:\n");
system("kill -l");
//注册SIGINT信号处理函数
signal(SIGINT, sigint_handler);
//创建子进程1
pid1 = fork();
if (pid1 < 0)
{
fprintf(stderr, "Failed to create child process 1\n");
exit(1);
}
else if (pid1 == 0)
{
//子进程1处理函数
printf("Child Process 1 is Created!\n");
while (1)
{
//等待信号
pause();
}
exit(0);
}
//创建子进程2
pid2 = fork();
if (pid2 < 0)
{
fprintf(stderr, "Failed to create child process 2\n");
exit(1);
}
else if (pid2 == 0)
{
//子进程2处理函数
printf("Child Process 2 is Created!\n");
while (1)
{
//等待信号
pause();
}
exit(0);
}
//父进程等待两个子进程终止
waitpid(pid1, &status, 0);
waitpid(pid2, &status, 0);
//输出信息后终止
printf("Parent Process is Killed!\n");
exit(0);
}
void sigint_handler(int signo)
{
//向两个子进程发送SIGUSR1信号
printf("Parent Process Caught the SIGINT Signal!\n");
kill(pid1, SIGUSR1);
kill(pid2, SIGUSR1);
}
```
在该程序中,首先使用`system`函数调用`kill -l`命令列出所有信号。然后,使用`signal`函数注册`SIGINT`信号处理函数`sigint_handler`,当父进程捕捉到`SIGINT`信号时,会向两个子进程发送`SIGUSR1`信号。
子进程1和子进程2都会进入一个死循环,等待信号的到来。当它们接收到`SIGUSR1`信号时,会输出相应的信息并终止。
父进程使用`waitpid`函数等待两个子进程的终止,并在两个子进程都终止后输出相应的信息并终止。