C Library Function - sigaction()
sigaction is a function in the C standard library used to inspect or modify the action associated with a specific signal. Compared with signal function,sigaction provides more control and better portability.
Syntax
int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact);
Parameters
int sig: The signal number to inspect or modify. Common signals includeSIGINT,SIGTERM,SIGKILL, etc.const struct sigaction *act: A pointer to the new signal-handling action. If it isNULL, the current signal-handling action is not modified.struct sigaction *oldact: A pointer used to save the old signal-handling action. If it isNULL, the old signal-handling action is not saved.
struct sigaction Structure
struct sigaction {
void (*sa_handler)(int); // 信号处理函数指针
void (*sa_sigaction)(int, siginfo_t *, void *); // 信号处理函数指针(扩展)
sigset_t sa_mask; // 在处理该信号时要阻塞的信号集
int sa_flags; // 修改信号行为的选项
void (*sa_restorer)(void); // 恢复函数,已废弃
};
sa_flags common options
SA_RESTART: Automatically restart system calls interrupted by the signal.SA_SIGINFO: When usingsa_sigactioninstead ofsa_handleras the signal handler.SA_NOCLDSTOP: IfsigIsSIGCHLD, the signal is not generated when a child process stops or continues.
Return Value
- Returns 0 on success.
- Returns -1 on failure and sets
errnoto indicate the error type.
Example
The following is a simple example program demonstrating how to use the sigaction The function sets SIGINT the handler for the signal:
Example
#include
#include
#include
// Custom signal handler function
void
handle_sigint
(
int
sig
)
{
printf
(
"Caught signal %d\n"
,
sig
)
;
}
int
main
(
)
{
struct
sigaction sa
;
// Set the handler to handle_sigint
sa.
sa_handler
=
handle_sigint
;
sigemptyset
(
&
sa.
sa_mask
)
;
sa.
sa_flags
=
0
;
// Use sigaction to set the new signal-handling action
if
(
sigaction
(
SIGINT
,
&
sa
,
NULL
)
==
1
)
{
perror
(
"sigaction"
)
;
return
1
;
}
// Main loop, running continuously until a signal is caught
while
(
1
)
{
printf
(
"Running...\n"
)
;
sleep
(
1
)
;
}
return
0
;
}
After compiling and running the program, the output will be:
Running...
Running...
Running...
...
When Ctrl+C is pressed (sending a SIGINT signal), the output will be:
Caught signal 2
The program catches the SIGINT signal and executes the custom signal handler handle_sigint, then continues running the main loop.
Notes
sigactionThe function provides more features thansignalfunction, allowing you to set the signal handler, signal mask, and signal-handling options.- A signal handler should be as short as possible, because other signals are blocked while handling a signal. If a signal handler runs too long, it may affect the program's real-time performance.
- Some signals (such as
SIGKILLandSIGSTOP) cannot be caught or ignored.
C Standard Library -