linux 信号 发送和接收的代码示例
时间: 2023-06-01 21:06:34 浏览: 91
以下是一个简单的发送和接收 Linux 信号的代码示例:
发送信号的代码:
```c
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
int main() {
pid_t pid = getpid();
int ret = kill(pid, SIGUSR1); // 发送一个 SIGUSR1 信号到当前进程
if (ret == -1) {
perror("kill error");
return 1;
}
return 0;
}
```
接收信号的代码:
```c
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void handler(int sig) {
printf("received signal %d\n", sig);
}
int main() {
struct sigaction act;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
act.sa_handler = handler;
if (sigaction(SIGUSR1, &act, NULL) == -1) { // 注册一个 SIGUSR1 信号处理函数
perror("sigaction error");
return 1;
}
for (;;) { // 无限循环,等待接收信号
sleep(1);
}
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)