用系统调用signal()让父进程捕捉键盘上来的中断信号(Ctrl-C);
时间: 2024-02-12 07:06:43 浏览: 33
在 Unix/Linux 系统中,我们可以使用 signal() 系统调用来注册信号处理函数,以处理接收到的信号。为了让父进程能够捕捉键盘上来的中断信号(Ctrl-C),我们可以在父进程中调用 signal() 函数,注册 SIGINT 信号的处理函数。具体代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void sigint_handler(int sig) {
printf("Received signal %d\n", sig);
exit(0);
}
int main() {
signal(SIGINT, sigint_handler);
printf("My PID is %d\n", getpid());
while (1) {
printf("Waiting for signal...\n");
sleep(1);
}
return 0;
}
```
在上面的代码中,我们定义了一个 sigint_handler() 函数,用于处理 SIGINT 信号(即键盘上来的中断信号)。在 main() 函数中,我们调用 signal() 函数,将 SIGINT 信号的处理函数设置为 sigint_handler()。这样,当父进程接收到 SIGINT 信号时,就会调用 sigint_handler() 函数来处理它。在 sigint_handler() 函数中,我们打印出接收到的信号编号,然后调用 exit() 函数来退出进程。
在 main() 函数中,我们使用一个无限循环来等待信号的到来。每隔一秒钟打印一次提示信息,等待 SIGINT 信号的到来。如果接收到 SIGINT 信号,就会调用 sigint_handler() 函数来处理它,然后退出进程。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)