1、编写一段C语言程序,使其实现进程的软中断通信。 要求:使用系统调用fork( )创造一个进程,父进程进程睡眠2秒后,用系统调用Kill( ) 向子进程P发出信号,子进程P捕捉到信息后输出下列信息终止: Child is Killed by father! Father is killed 父进程等待子进程终止后,输出如下的信息后终止
时间: 2024-02-25 09:51:31 浏览: 29
好的,下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void handle(int signum)
{
printf("Child is Killed by father!\n");
exit(0);
}
int main()
{
pid_t pid;
pid = fork();
if(pid < 0)
{
printf("Fork failed!\n");
return -1;
}
else if(pid == 0)
{
signal(SIGINT, handle);
while(1);
}
else
{
sleep(2);
kill(pid, SIGINT);
printf("Father is killed!\n");
wait(NULL);
printf("Child process exit!\n");
}
return 0;
}
```
这里使用了 `fork()` 系统调用创建了一个子进程,父进程等待2秒后向子进程发送 `SIGINT` 信号(即中断信号)。子进程使用 `signal()` 函数来注册信号处理函数 `handle()`,一旦接收到 `SIGINT` 信号就会执行该函数并退出进程。
父进程使用 `kill()` 函数向子进程发送信号,然后等待子进程终止。子进程接收到信号后执行信号处理函数并退出,父进程在 `wait()` 函数中等待子进程退出,并在子进程退出后输出信息并退出。
需要注意的是,这里的信号传递只是一种简单的进程间通信方式,如果需要传递更复杂的信息,需要使用其他的进程通信方式。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)