C Library Function - sigprocmask()
Description
In C language,sigprocmaskThe function is used to examine or change the signal mask of the current process. The signal mask determines which signals are blocked during masking, that is, temporarily not processed.
Syntax
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset);
Parameters
int how: operation flag, determining how to change the signal mask:SIG_BLOCK: add the signals in the signal set pointed to bysetto the current signal mask.SIG_UNBLOCK: remove from the current signal masksetthe signals in the signal set pointed to by .SIG_SETMASK: replace the current signal mask withsetthe signal set pointed to by .
const sigset_t *set: a pointer to the new signal set to be set.sigset_t *oldset: if notNULL, stores the previous signal mask.
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 sigprocmask function to block SIGINT signal, then unblock and view the previous signal mask:
Example
#include
#include
#include
int
main
(
)
{
sigset_t new_mask
,
old_mask
;
// initialize the new signal set to contain only SIGINT
sigemptyset
(
&
new_mask
)
;
sigaddset
(
&
new_mask
,
SIGINT
)
;
// set the new signal mask to block the SIGINT signal
if
(
sigprocmask
(
SIG_BLOCK
,
&
new_mask
,
&
old_mask
)
==
1
)
{
perror
(
"sigprocmask"
)
;
return
1
;
}
printf
(
"SIGINT signal is blocked. Sleeping for 5 seconds...\n"
)
;
sleep
(
5
)
;
// unblock SIGINT
if
(
sigprocmask
(
SIG_UNBLOCK
,
&
new_mask
,
NULL
)
==
1
)
{
perror
(
"sigprocmask"
)
;
return
1
;
}
printf
(
"SIGINT signal is unblocked.\n"
)
;
return
0
;
}
Output result
Running the above example program may produce the following output:
SIGINT signal is blocked. Sleeping for 5 seconds...
During this period, the SIGINT signal is blocked, so the program waits for 5 seconds.
SIGINT signal is unblocked.
Then, the program unblocks SIGINT signal and resumes normal handling of the signal.
Notes
- Use
sigprocmaskBe careful when using the function, ensuring that critical signals (such asSIGKILLorSIGSTOP) are not blocked for a long time, and these signals cannot be blocked or caught. sigprocmaskThe function can be used to control signal handling in critical sections, such as avoiding handling interrupt signals within a critical region.
C Standard Library -