在linux中,编写一段C语言程序,使其实现进程的软中断通信。 要求:使用系统调用fork( )创造一个进程,父进程进程睡眠2秒后,用系统调用Kill( ) 向子进程P发出信号,子进程P捕捉到信息后输出下列信息终止: Child is Killed by father! 父进程等待子进程终止后,输出I am your father!后终止。
时间: 2024-02-25 08:52:23 浏览: 76
好的,下面是实现进程软中断通信的C语言程序:
```c
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
void child_process(int sig)
{
printf("Child is Killed by father!\n");
exit(0);
}
int main()
{
pid_t pid;
pid = fork();
if (pid == -1)
{
printf("Failed to create process!\n");
exit(-1);
}
else if (pid == 0) // 子进程
{
signal(SIGINT, child_process); // 注册信号处理函数
while (1)
sleep(1);
}
else // 父进程
{
sleep(2); // 父进程睡眠2秒
kill(pid, SIGINT); // 向子进程发送信号
wait(NULL); // 等待子进程退出
printf("I am your father!\n");
}
return 0;
}
```
程序运行时,先用系统调用fork()创建一个子进程,父进程睡眠2秒后向子进程发送SIGINT信号,子进程捕捉到信号后输出“Child is Killed by father!”并退出,父进程等待子进程退出后输出“I am your father!”后终止。
阅读全文