sigaction - examine and change a signal action
[CX]#include <signal.h>
int sigaction(intsig, const struct sigaction *restrictact,
struct sigaction *restrictoact);
Thesigaction() function allows the calling process to examine and/or specify the action to be associated with a specificsignal. The argumentsig specifies the signal; acceptable values are defined in<signal.h>.
The structuresigaction, used to describe an action to be taken, is defined in the<signal.h> header to include at least the following members:
Member Type
Member Name
Description
void(*) (int)
sa_handler
Pointer to a signal-catching function or one of the macros SIG_IGN or SIG_DFL.
sigset_t
sa_mask
Additional set of signals to be blocked during execution of signal-catching function.
int
sa_flags
Special flags to affect behavior of signal.
void(*) (int,
siginfo_t *, void *)sa_sigaction
Pointer to a signal-catching function.
The storage occupied bysa_handler andsa_sigaction may overlap, and a conforming application shall not use bothsimultaneously.
If the argumentact is not a null pointer, it points to a structure specifying the action to be associated with thespecified signal. If the argumentoact is not a null pointer, the action previously associated with the signal is stored inthe location pointed to by the argumentoact. If the argumentact is a null pointer, signal handling is unchanged;thus, the call can be used to enquire about the current handling of a given signal. The SIGKILL and SIGSTOP signals shall not beadded to the signal mask using this mechanism; this restriction shall be enforced by the system without causing an error to beindicated.
If the SA_SIGINFO flag (see below) is cleared in thesa_flags field of thesigaction structure, thesa_handler field identifies the action to be associated with the specified signal. If the SA_SIGINFO flag is set in thesa_flags field, thesa_sigaction field specifies a signal-catching function.
Thesa_flags field can be used to modify the behavior of the specified signal.
The following flags, defined in the<signal.h> header, can be set insa_flags:
- SA_NOCLDSTOP
- Do not generate SIGCHLD when children stop[XSI]
or stopped children continue.
Ifsig is SIGCHLD and the SA_NOCLDSTOP flag is not set insa_flags, and the implementation supports the SIGCHLDsignal, then a SIGCHLD signal shall be generated for the calling process whenever any of its child processes stop[XSI]
and aSIGCHLD signal may be generated for the calling process whenever any of its stopped child processes are continued.
Ifsig is SIGCHLD and the SA_NOCLDSTOP flag is set insa_flags, then the implementation shall not generate a SIGCHLD signal in this way.
- SA_ONSTACK
- [XSI]
If set and an alternate signal stack has been declared withsigaltstack(), thesignal shall be delivered to the calling process on that stack. Otherwise, the signal shall be delivered on the current stack.
- SA_RESETHAND
- If set, the disposition of the signal shall be reset to SIG_DFL and the SA_SIGINFO flag shall be cleared on entry to the signalhandler.
- Note:
- SIGILL and SIGTRAP cannot be automatically reset when delivered; the system silently enforces this restriction.
Otherwise, the disposition of the signal shall not be modified on entry to the signal handler. In addition, if this flag is set,sigaction() may behave as if the SA_NODEFER flag were also set.
- SA_RESTART
- This flag affects the behavior of interruptible functions; that is, those specified to fail witherrno set to [EINTR].If set, and a function specified as interruptible is interrupted by this signal, the function shall restart and shall not fail with[EINTR] unless otherwise specified. If an interruptible function which uses a timeout is restarted, the duration of the timeoutfollowing the restart is set to an unspecified value that does not exceed the original timeout value. If the flag is not set,interruptible functions interrupted by this signal shall fail witherrno set to [EINTR].
- SA_SIGINFO
- If cleared and the signal is caught, the signal-catching function shall be entered as:
void func(intsigno);wheresigno is the only argument to the signal-catching function. In this case, the application shall use thesa_handler member to describe the signal-catching function and the application shall not modify thesa_sigactionmember.
If SA_SIGINFO is set and the signal is caught, the signal-catching function shall be entered as:
void func(intsigno, siginfo_t *info, void *context);where two additional arguments are passed to the signal-catching function. The second argument shall point to an object of typesiginfo_t explaining the reason why the signal was generated; the third argument can be cast to a pointer to an object oftypeucontext_t to refer to the receiving thread's context that was interrupted when the signal was delivered. In this case,the application shall use thesa_sigaction member to describe the signal-catching function and the application shall notmodify thesa_handler member.
Thesi_signo member contains the system-generated signal number.
[XSI]
Thesi_errno member may contain implementation-defined additional error information; if non-zero, it contains an errornumber identifying the condition that caused the signal to be generated.
Thesi_code member contains a code identifying the cause of the signal, as described inSignal Actions.
- SA_NOCLDWAIT
- [XSI]
Ifsig does not equal SIGCHLD, the behavior is unspecified. Otherwise, the behavior of the SA_NOCLDWAIT flag is as specifiedinConsequences of Process Termination.
- SA_NODEFER
- If set andsig is caught,sig shall not be added to the thread's signal mask on entry to the signal handlerunless it is included insa_mask. Otherwise,sig shall always be added to the thread's signal mask on entry to thesignal handler.
When a signal is caught by a signal-catching function installed bysigaction(), a new signal mask is calculated andinstalled for the duration of the signal-catching function (or until a call to eithersigprocmask() orsigsuspend() ismade). This mask is formed by taking the union of the current signal mask and the value of thesa_mask for the signal beingdelivered, and unless SA_NODEFER or SA_RESETHAND is set, then including the signal being delivered. If and when the user's signalhandler returns normally, the original signal mask is restored.
Once an action is installed for a specific signal, it shall remain installed until another action is explicitly requested (byanother call tosigaction()), until the SA_RESETHAND flag causes resetting of the handler, or until one of theexec functions is called.
If the previous action forsig had been established bysignal(), the valuesof the fields returned in the structure pointed to byoact are unspecified, and in particularoact->sa_handler is not necessarily the same value passed tosignal(). However, if apointer to the same structure or a copy thereof is passed to a subsequent call tosigaction() via theact argument,handling of the signal shall be as if the original call tosignal() wererepeated.
Ifsigaction() fails, no new signal handler is installed.
It is unspecified whether an attempt to set the action for a signal that cannot be caught or ignored to SIG_DFL is ignored orcauses an error to be returned witherrno set to [EINVAL].
If SA_SIGINFO is not set insa_flags, then the disposition of subsequent occurrences ofsig when it is alreadypending is implementation-defined; the signal-catching function shall be invoked with a single argument. If SA_SIGINFO is set insa_flags, then subsequent occurrences ofsig generated bysigqueue()or as a result of any signal-generating function that supports the specification of an application-defined value (whensigis already pending) shall be queued in FIFO order until delivered or accepted; the signal-catching function shall be invoked withthree arguments. The application specified value is passed to the signal-catching function as thesi_value member of thesiginfo_t structure.
The result of the use ofsigaction() and asigwait() function concurrentlywithin a process on the same signal is unspecified.
Upon successful completion,sigaction() shall return 0; otherwise, -1 shall be returned,errno shall be set toindicate the error, and no new signal-catching function shall be installed.
Thesigaction() function shall fail if:
- [EINVAL]
- Thesig argument is not a valid signal number or an attempt is made to catch a signal that cannot be caught or ignore asignal that cannot be ignored.
Thesigaction() function may fail if:
- [EINVAL]
- An attempt was made to set the action to SIG_DFL for a signal that cannot be caught or ignored (or both).
In addition, on systems that do not support the XSI option, thesigaction() function may fail if the SA_SIGINFO flag isset in thesa_flags field of thesigaction structure for a signal not in the range SIGRTMIN to SIGRTMAX.
Establishing a Signal Handler
The following example demonstrates the use ofsigaction() to establish a handler for the SIGINT signal.
#include <signal.h>
static void handler(int signum){ /* Take appropriate actions for signal delivery */}
int main(){ struct sigaction sa;
sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; /* Restart functions if interrupted by handler */ if (sigaction(SIGINT, &sa, NULL) == -1) /* Handle error */;
/* Further code */}
Thesigaction() function supersedes thesignal() function, and should beused in preference. In particular,sigaction() andsignal() should not be usedin the same process to control the same signal. The behavior of async-signal-safe functions, as defined in their respectiveDESCRIPTION sections, is as specified by this volume of POSIX.1-2017, regardless of invocation from a signal-catching function.This is the only intended meaning of the statement that async-signal-safe functions may be used in signal-catching functionswithout restrictions. Applications must still consider all effects of such functions on such things as data structures, files, andprocess state. In particular, application developers need to consider the restrictions on interactions when interruptingsleep() and interactions among multiple handles for a file description. The fact that anyspecific function is listed as async-signal-safe does not necessarily mean that invocation of that function from a signal-catchingfunction is recommended.
In order to prevent errors arising from interrupting non-async-signal-safe function calls, applications should protect calls tothese functions either by blocking the appropriate signals or through the use of some programmatic semaphore (seesemget,sem_init,sem_open, and so on). Note in particular that even the "safe" functions may modifyerrno; the signal-catching function, if not executing as an independent thread, should save and restore its value in orderto avoid the possibility that delivery of a signal in between an error return from a function that setserrno and thesubsequent examination oferrno could result in the signal-catching function changing the value oferrno. Naturally,the same principles apply to the async-signal-safety of application routines and asynchronous data access. Note thatlongjmp() andsiglongjmp() are not in thelist of async-signal-safe functions. This is because the code executing afterlongjmp() andsiglongjmp() can call anyunsafe functions with the same danger as calling those unsafe functions directly from the signal handler. Applications that uselongjmp() andsiglongjmp() fromwithin signal handlers require rigorous protection in order to be portable. Many of the other functions that are excluded from thelist are traditionally implemented using eithermalloc() orfree() functions or the standard I/O library, both of which traditionally use data structuresin a non-async-signal-safe manner. Since any combination of different functions using a common data structure can causeasync-signal-safety problems, this volume of POSIX.1-2017 does not define the behavior when any unsafe function is called in asignal handler that interrupts an unsafe function.
Usually, the signal is executed on the stack that was in effect before the signal was delivered. An alternate stack may bespecified to receive a subset of the signals being caught.
When the signal handler returns, the receiving thread resumes execution at the point it was interrupted unless the signalhandler makes other arrangements. Iflongjmp() or_longjmp() is used to leave the signal handler, then the signal mask must be explicitlyrestored.
This volume of POSIX.1-2017 defines the third argument of a signal handling function when SA_SIGINFO is set as avoid *instead of aucontext_t *, but without requiring type checking. New applications should explicitly cast the third argumentof the signal handling function toucontext_t *.
The BSD optional four argument signal handling function is not supported by this volume of POSIX.1-2017. The BSD declarationwould be:
void handler(intsig, intcode, struct sigcontext *scp, char *addr);wheresig is the signal number,code is additional information on certain signals,scp is a pointer to thesigcontext structure, andaddr is additional address information. Much the same information is available in theobjects pointed to by the second argument of the signal handler specified when SA_SIGINFO is set.
Since thesigaction() function is allowed but not required to set SA_NODEFER when the application sets the SA_RESETHANDflag, applications which depend on the SA_RESETHAND functionality for the newly installed signal handler must always explicitly setSA_NODEFER when they set SA_RESETHAND in order to be portable.
See also the rationale for Realtime Signal Generation and Delivery in XRATRealtime Signal Generation and Delivery.
Although this volume of POSIX.1-2017 requires that signals that cannot be ignored shall not be added to the signal mask when asignal-catching function is entered, there is no explicit requirement that subsequent calls tosigaction() reflect this inthe information returned in theoact argument. In other words, if SIGKILL is included in thesa_mask field ofact, it is unspecified whether or not a subsequent call tosigaction() returns with SIGKILL included in thesa_mask field ofoact.
The SA_NOCLDSTOP flag, when supplied in theact->sa_flags parameter, allows overloading SIGCHLD with theSystem V semantics that each SIGCLD signal indicates a single terminated child. Most conforming applications that catch SIGCHLD areexpected to install signal-catching functions that repeatedly call thewaitpid()function with the WNOHANG flag set, acting on each child for which status is returned, untilwaitpid() returns zero. If stopped children are not of interest, the use of the SA_NOCLDSTOPflag can prevent the overhead from invoking the signal-catching routine when they stop.
Some historical implementations also define other mechanisms for stopping processes, such as theptrace() function. Theseimplementations usually do not generate a SIGCHLD signal when processes stop due to this mechanism; however, that is beyond thescope of this volume of POSIX.1-2017.
This volume of POSIX.1-2017 requires that calls tosigaction() that supply a NULLact argument succeed, even inthe case of signals that cannot be caught or ignored (that is, SIGKILL or SIGSTOP). The System Vsignal() and BSDsigvec() functions return [EINVAL] in these cases and, in thisrespect, their behavior varies fromsigaction().
This volume of POSIX.1-2017 requires thatsigaction() properly save and restore a signal action set up by the ISO Cstandardsignal() function. However, there is no guarantee that the reverse is true,nor could there be given the greater amount of information conveyed by thesigaction structure. Because of this,applications should avoid using both functions for the same signal in the same process. Since this cannot always be avoided in caseof general-purpose library routines, they should always be implemented withsigaction().
It was intended that thesignal() function should be implementable as a libraryroutine usingsigaction().
The POSIX Realtime Extension extends thesigaction() function as specified by the POSIX.1-1990 standard to allow theapplication to request on a per-signal basis via an additional signal action flag that the extra parameters, including theapplication-defined signal value, if any, be passed to the signal-catching function.
None.
Signal Concepts,exec,_Exit,kill,_longjmp,longjmp,pthread_sigmask,raise,semget,sem_init,sem_open,sigaddset,sigaltstack,sigdelset,sigemptyset,sigfillset,sigismember,signal,sigsuspend,wait,waitid
XBD<signal.h>
First released in Issue 3. Included for alignment with the POSIX.1-1988 standard.
The DESCRIPTION is updated for alignment with the POSIX Realtime Extension and POSIX Threads Extension.
In the DESCRIPTION, the second argument tofunc when SA_SIGINFO is set is no longer permitted to be NULL, and thedescription of permittedsiginfo_t contents is expanded by reference to<signal.h>.
Since the X/OPEN UNIX Extension functionality is now folded into the BASE, the [ENOTSUP] error is deleted.
The Open Group Corrigendum U028/7 is applied. In the paragraph entitled "Signal Effects on Other Functions", a reference tosigpending() is added.
In the DESCRIPTION, the text "Signal Generation and Delivery", "Signal Actions", and "Signal Effects on Other Functions''are moved to a separate section of this volume of POSIX.1-2008.
Text describing functionality from the Realtime Signals Extension option is marked.
The following changes are made for alignment with the ISO POSIX-1:1996 standard:
The [ENOTSUP] error condition is added.
The normative text is updated to avoid use of the term "must" for application requirements.
Therestrict keyword is added to thesigaction() prototype for alignment with the ISO/IEC 9899:1999standard.
References to thewait3() function are removed.
The SYNOPSIS is marked CX since the presence of this function in the<signal.h> header is an extension over the ISO C standard.
IEEE Std 1003.1-2001/Cor 1-2002, item XSH/TC1/D6/57 is applied, changing text in the table describing thesigaction structure.
IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/127 is applied, removing text from the DESCRIPTION duplicatedlater in the same section.
IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/128 is applied, updating the DESCRIPTION and APPLICATION USAGEsections. Changes are made to refer to the thread rather than the process.
IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/129 is applied, adding the example to the EXAMPLES section.
Austin Group Interpretation 1003.1-2001 #004 is applied.
Austin Group Interpretations 1003.1-2001 #065 and #084 are applied, clarifying the role of the SA_NODEFER flag with respect tothe signal mask, and clarifying the SA_RESTART flag for interrupted functions which use timeouts.
Austin Group Interpretation 1003.1-2001 #156 is applied.
SD5-XSH-ERN-167 is applied, updating the APPLICATION USAGE section.
SD5-XSH-ERN-172 is applied, updating the DESCRIPTION to make optional the requirement that when the SA_RESETHAND flag is set,sigaction() shall behave as if the SA_NODEFER flag were also set.
Functionality relating to the Realtime Signals Extension option is moved to the Base.
The description of thesi_code member is replaced with a reference toSignal Actions.
POSIX.1-2008, Technical Corrigendum 1, XSH/TC1-2008/0578 [66] and XSH/TC1-2008/0579 [140] are applied.
POSIX.1-2008, Technical Corrigendum 2, XSH/TC2-2008/0329 [690] and XSH/TC2-2008/0330 [491] are applied.
return to top of page