linux捕获信号的有哪些方法
在Linux中,捕获信号的方法有两种:
1. 使用信号处理函数:可以通过使用signal()函数来注册信号处理函数,该函数的原型以下:
```c
void (*signal(int sig, void (*handler)(int)))(int);
```
其中,sig是要捕获的信号的编号,handler是信号处理函数的指针。当信号产生时,系统会调用注册的信号处理函数来处理该信号。
例如,以下代码演示了如何捕获并处理SIGINT信号:
```c
#include
#include
#include
void sigint_handler(int sig)
{
printf("Caught SIGINT signal
");
// 这里可以进行信号处理的逻辑
}
int main()
{
signal(SIGINT, sigint_handler);
while (1) {
sleep(1);
}
return 0;
}
```
2. 使用sigaction()函数:sigaction()函数提供了更加灵活和可靠的信号处理方式,其原型以下:
```c
int sigaction(int sig, const struct sigaction *restrict act,
struct sigaction *restrict oact);
```
其中,sig是要捕获的信号的编号,act是指向sigaction结构的指针,该结构包括信号处理函数的信息。
以下代码演示了怎样使用sigaction()函数捕获并处理SIGINT信号:
```c
#include
#include
#include
void sigint_handler(int sig)
{
printf("Caught SIGINT signal
");
// 这里可以进行信号处理的逻辑
}
int main()
{
struct sigaction sa;
sa.sa_handler = sigint_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGINT, &sa, NULL);
while (1) {
sleep(1);
}
return 0;
}
```
不管是使用signal()函数或sigaction()函数,捕获的信号产生时,系统会调用注册的信号处理函数来处理该信号。
TOP