1 @node Signal Handling, Process Startup, Non-Local Exits, Top
2 @chapter Signal Handling
5 A @dfn{signal} is a software interrupt delivered to a process. The
6 operating system uses signals to report exceptional situations to an
7 executing program. Some signals report errors such as references to
8 invalid memory addresses; others report asynchronous events, such as
9 disconnection of a phone line.
11 The GNU C library defines a variety of signal types, each for a
12 particular kind of event. Some kinds of events make it inadvisable or
13 impossible for the program to proceed as usual, and the corresponding
14 signals normally abort the program. Other kinds of signals that report
15 harmless events are ignored by default.
17 If you anticipate an event that causes signals, you can define a handler
18 function and tell the operating system to run it when that particular
19 type of signal arrives.
21 Finally, one process can send a signal to another process; this allows a
22 parent process to abort a child, or two related processes to communicate
26 * Concepts of Signals:: Introduction to the signal facilities.
27 * Standard Signals:: Particular kinds of signals with
28 standard names and meanings.
29 * Signal Actions:: Specifying what happens when a
30 particular signal is delivered.
31 * Defining Handlers:: How to write a signal handler function.
32 * Interrupted Primitives:: Signal handlers affect use of @code{open},
33 @code{read}, @code{write} and other functions.
34 * Generating Signals:: How to send a signal to a process.
35 * Blocking Signals:: Making the system hold signals temporarily.
36 * Waiting for a Signal:: Suspending your program until a signal
38 * BSD Signal Handling:: Additional functions for backward
39 compatibility with BSD.
40 * BSD Handler:: BSD Function to Establish a Handler.
43 @node Concepts of Signals
44 @section Basic Concepts of Signals
46 This section explains basic concepts of how signals are generated, what
47 happens after a signal is delivered, and how programs can handle
51 * Kinds of Signals:: Some examples of what can cause a signal.
52 * Signal Generation:: Concepts of why and how signals occur.
53 * Delivery of Signal:: Concepts of what a signal does to the
57 @node Kinds of Signals
58 @subsection Some Kinds of Signals
60 A signal reports the occurrence of an exceptional event. These are some
61 of the events that can cause (or @dfn{generate}, or @dfn{raise}) a
66 A program error such as dividing by zero or issuing an address outside
70 A user request to interrupt or terminate the program. Most environments
71 are set up to let a user suspend the program by typing @kbd{C-z}, or
72 terminate it with @kbd{C-c}. Whatever key sequence is used, the
73 operating system sends the proper signal to interrupt the process.
76 The termination of a child process.
79 Expiration of a timer or alarm.
82 A call to @code{kill} or @code{raise} by the same process.
85 A call to @code{kill} from another process. Signals are a limited but
86 useful form of interprocess communication.
89 Each of these kinds of events (excepting explicit calls to @code{kill}
90 and @code{raise}) generates its own particular kind of signal. The
91 various kinds of signals are listed and described in detail in
92 @ref{Standard Signals}.
94 @node Signal Generation
95 @subsection Concepts of Signal Generation
96 @cindex generation of signals
98 In general, the events that generate signals fall into three major
99 categories: errors, external events, and explicit requests.
101 An error means that a program has done something invalid and cannot
102 continue execution. But not all kinds of errors generate signals---in
103 fact, most do not. For example, opening a nonexistant file is an error,
104 but it does not raise a signal; instead, @code{open} returns @code{-1}.
105 In general, errors that are necessarily associated with certain library
106 functions are reported by returning a value that indicates an error.
107 The errors which raise signals are those which can happen anywhere in
108 the program, not just in library calls. These include division by zero
109 and invalid memory addresses.
111 An external event generally has to do with I/O or other processes.
112 These include the arrival of input, the expiration of a timer, and the
113 termination of a child process.
115 An explicit request means the use of a library function such as
116 @code{kill} whose purpose is specifically to generate a signal.
118 Signals may be generated @dfn{synchronously} or @dfn{asynchronously}. A
119 synchronous signal pertains to a specific action in the program, and is
120 delivered (unless blocked) during that action. Errors generate signals
121 synchronously, and so do explicit requests by a process to generate a
122 signal for that same process.
124 Asynchronous signals are generated by events outside the control of the
125 process that receives them. These signals arrive at unpredictable times
126 during execution. External events generate signals asynchronously, and
127 so do explicit requests that apply to some other process.
129 A given type of signal is either typically synchrous or typically
130 asynchronous. For example, signals for errors are typically synchronous
131 because errors generate signals synchronously. But any type of signal
132 can be generated synchronously or asynchronously with an explicit
135 @node Delivery of Signal
136 @subsection How Signals Are Delivered
137 @cindex delivery of signals
138 @cindex pending signals
139 @cindex blocked signals
141 When a signal is generated, it becomes @dfn{pending}. Normally it
142 remains pending for just a short period of time and then is
143 @dfn{delivered} to the process that was signaled. However, if that kind
144 of signal is currently @dfn{blocked}, it may remain pending
145 indefinitely---until signals of that kind are @dfn{unblocked}. Once
146 unblocked, it will be delivered immediately. @xref{Blocking Signals}.
148 @cindex specified action (for a signal)
149 @cindex default action (for a signal)
150 @cindex signal action
151 @cindex catching signals
152 When the signal is delivered, whether right away or after a long delay,
153 the @dfn{specified action} for that signal is taken. For certain
154 signals, such as @code{SIGKILL} and @code{SIGSTOP}, the action is fixed,
155 but for most signals, the program has a choice: ignore the signal,
156 specify a @dfn{handler function}, or accept the @dfn{default action} for
157 that kind of signal. The program specifies its choice using functions
158 such as @code{signal} or @code{sigaction} (@pxref{Signal Actions}). We
159 sometimes say that a handler @dfn{catches} the signal. While the
160 handler is running, that particular signal is normally blocked.
162 If the specified action for a kind of signal is to ignore it, then any
163 such signal which is generated is discarded immediately. This happens
164 even if the signal is also blocked at the time. A signal discarded in
165 this way will never be delivered, not even if the program subsequently
166 specifies a different action for that kind of signal and then unblocks
169 If a signal arrives which the program has neither handled nor ignored,
170 its @dfn{default action} takes place. Each kind of signal has its own
171 default action, documented below (@pxref{Standard Signals}). For most kinds
172 of signals, the default action is to terminate the process. For certain
173 kinds of signals that represent ``harmless'' events, the default action
176 When a signal terminates a process, its parent process can determine the
177 cause of termination by examining the termination status code reported
178 by the @code{wait} or @code{waitpid} functions. (This is discussed in
179 more detail in @ref{Process Completion}.) The information it can get
180 includes the fact that termination was due to a signal, and the kind of
181 signal involved. If a program you run from a shell is terminated by a
182 signal, the shell typically prints some kind of error message.
184 The signals that normally represent program errors have a special
185 property: when one of these signals terminates the process, it also
186 writes a @dfn{core dump file} which records the state of the process at
187 the time of termination. You can examine the core dump with a debugger
188 to investigate what caused the error.
190 If you raise a ``program error'' signal by explicit request, and this
191 terminates the process, it makes a core dump file just as if the signal
192 had been due directly to an error.
194 @node Standard Signals
195 @section Standard Signals
197 @cindex names of signals
200 @cindex signal number
201 This section lists the names for various standard kinds of signals and
202 describes what kind of event they mean. Each signal name is a macro
203 which stands for a positive integer---the @dfn{signal number} for that
204 kind of signal. Your programs should never make assumptions about the
205 numeric code for a particular kind of signal, but rather refer to them
206 always by the names defined here. This is because the number for a
207 given kind of signal can vary from system to system, but the meanings of
208 the names are standardized and fairly uniform.
210 The signal names are defined in the header file @file{signal.h}.
214 @deftypevr Macro int NSIG
215 The value of this symbolic constant is the total number of signals
216 defined. Since the signal numbers are allocated consecutively,
217 @code{NSIG} is also one greater than the largest defined signal number.
221 * Program Error Signals:: Used to report serious program errors.
222 * Termination Signals:: Used to interrupt and/or terminate the
224 * Alarm Signals:: Used to indicate expiration of timers.
225 * Asynchronous I/O Signals:: Used to indicate input is available.
226 * Job Control Signals:: Signals used to support job control.
227 * Miscellaneous Signals:: Miscellaneous Signals.
228 * Nonstandard Signals:: Implementations can support other signals.
229 * Signal Messages:: Printing a message describing a signal.
232 @node Program Error Signals
233 @subsection Program Error Signals
234 @cindex program error signals
236 The following signals are generated when a serious program error is
237 detected by the operating system or the computer itself. In general,
238 all of these signals are indications that your program is seriously
239 broken in some way, and there's usually no way to continue the
240 computation which encountered the error.
242 Some programs handle program error signals in order to tidy up before
243 terminating; for example, programs that turn off echoing of terminal
244 input should handle program error signals in order to turn echoing back
245 on. The handler should end by specifying the default action for the
246 signal that happened and then reraising it; this will cause the program
247 to terminate with that signal, as if it had not had a handler.
248 (@xref{Termination in Handler}.)
250 Termination is the sensible ultimate outcome from a program error in
251 most programs. However, programming systems such as Lisp that can load
252 compiled user programs might need to keep executing even if a user
253 program incurs an error. These programs have handlers which use
254 @code{longjmp} to return control to the command level.
256 The default action for all of these signals is to cause the process to
257 terminate. If you block or ignore these signals or establish handlers
258 for them that return normally, your program will probably break horribly
259 when such signals happen, unless they are generated by @code{raise} or
260 @code{kill} instead of a real error.
263 When one of these program error signals terminates a process, it also
264 writes a @dfn{core dump file} which records the state of the process at
265 the time of termination. The core dump file is named @file{core} and is
266 written in whichever directory is current in the process at the time.
267 (On the GNU system, you can specify the file name for core dumps with
268 the environment variable @code{COREFILE}.) The purpose of core dump
269 files is so that you can examine them with a debugger to investigate
270 what caused the error.
274 @deftypevr Macro int SIGFPE
275 The @code{SIGFPE} signal reports a fatal arithmetic error. Although the
276 name is derived from ``floating-point exception'', this signal actually
277 covers all arithmetic errors, including division by zero and overflow.
278 If a program stores integer data in a location which is then used in a
279 floating-point operation, this often causes an ``invalid operation''
280 exception, because the processor cannot recognize the data as a
281 floating-point number.
283 @cindex floating-point exception
285 Actual floating-point exceptions are a complicated subject because there
286 are many types of exceptions with subtly different meanings, and the
287 @code{SIGFPE} signal doesn't distinguish between them. The @cite{IEEE
288 Standard for Binary Floating-Point Arithmetic (ANSI/IEEE Std 754-1985)}
289 defines various floating-point exceptions and requires conforming
290 computer systems to report their occurrences. However, this standard
291 does not specify how the exceptions are reported, or what kinds of
292 handling and control the operating system can offer to the programmer.
295 BSD systems provide the @code{SIGFPE} handler with an extra argument
296 that distinguishes various causes of the exception. In order to access
297 this argument, you must define the handler to accept two arguments,
298 which means you must cast it to a one-argument function type in order to
299 establish the handler. The GNU library does provide this extra
300 argument, but the value is meaningful only on operating systems that
301 provide the information (BSD systems and GNU systems).
306 @item FPE_INTOVF_TRAP
307 @vindex FPE_INTOVF_TRAP
308 Integer overflow (impossible in a C program unless you enable overflow
309 trapping in a hardware-specific fashion).
312 @item FPE_INTDIV_TRAP
313 @vindex FPE_INTDIV_TRAP
314 Integer division by zero.
317 @item FPE_SUBRNG_TRAP
318 @vindex FPE_SUBRNG_TRAP
319 Subscript-range (something that C programs never check for).
322 @item FPE_FLTOVF_TRAP
323 @vindex FPE_FLTOVF_TRAP
324 Floating overflow trap.
327 @item FPE_FLTDIV_TRAP
328 @vindex FPE_FLTDIV_TRAP
329 Floating/decimal division by zero.
332 @item FPE_FLTUND_TRAP
333 @vindex FPE_FLTUND_TRAP
334 Floating underflow trap. (Trapping on floating underflow is not
338 @item FPE_DECOVF_TRAP
339 @vindex FPE_DECOVF_TRAP
340 Decimal overflow trap. (Only a few machines have decimal arithmetic and
342 @ignore @c These seem redundant
345 @item FPE_FLTOVF_FAULT
346 @vindex FPE_FLTOVF_FAULT
347 Floating overflow fault.
350 @item FPE_FLTDIV_FAULT
351 @vindex FPE_FLTDIV_FAULT
352 Floating divide by zero fault.
355 @item FPE_FLTUND_FAULT
356 @vindex FPE_FLTUND_FAULT
357 Floating underflow fault.
363 @deftypevr Macro int SIGILL
364 The name of this signal is derived from ``illegal instruction''; it
365 means your program is trying to execute garbage or a privileged
366 instruction. Since the C compiler generates only valid instructions,
367 @code{SIGILL} typically indicates that the executable file is corrupted,
368 or that you are trying to execute data. Some common ways of getting
369 into the latter situation are by passing an invalid object where a
370 pointer to a function was expected, or by writing past the end of an
371 automatic array (or similar problems with pointers to automatic
372 variables) and corrupting other data on the stack such as the return
373 address of a stack frame.
375 @cindex illegal instruction
379 @deftypevr Macro int SIGSEGV
380 @cindex segmentation violation
381 This signal is generated when a program tries to read or write outside
382 the memory that is allocated for it. (Actually, the signals only occur
383 when the program goes far enough outside to be detected by the system's
384 memory protection mechanism.) The name is an abbreviation for
385 ``segmentation violation''.
387 The most common way of getting a @code{SIGSEGV} condition is by
388 dereferencing a null or uninitialized pointer. A null pointer refers to
389 the address 0, and most operating systems make sure this address is
390 always invalid precisely so that dereferencing a null pointer will cause
391 @code{SIGSEGV}. (Some operating systems place valid memory at address
392 0, and dereferencing a null pointer does not cause a signal on these
393 systems.) As for uninitialized pointer variables, they contain random
394 addresses which may or may not be valid.
396 Another common way of getting into a @code{SIGSEGV} situation is when
397 you use a pointer to step through an array, but fail to check for the
403 @deftypevr Macro int SIGBUS
404 This signal is generated when an invalid pointer is dereferenced. Like
405 @code{SIGSEGV}, this signal is typically the result of dereferencing an
406 uninitialized pointer. The difference between the two is that
407 @code{SIGSEGV} indicates an invalid access to valid memory, while
408 @code{SIGBUS} indicates an access to an invalid address. In particular,
409 @code{SIGBUS} signals often result from dereferencing a misaligned
410 pointer, such as referring to a four-word integer at an address not
411 divisible by four. (Each kind of computer has its own requirements for
414 The name of this signal is an abbreviation for ``bus error''.
420 @deftypevr Macro int SIGABRT
422 This signal indicates an error detected by the program itself and
423 reported by calling @code{abort}. @xref{Aborting a Program}.
426 @node Termination Signals
427 @subsection Termination Signals
428 @cindex program termination signals
430 These signals are all used to tell a process to terminate, in one way
431 or another. They have different names because they're used for slightly
432 different purposes, and programs might want to handle them differently.
434 The reason for handling these signals is usually so your program can
435 tidy up as appropriate before actually terminating. For example, you
436 might want to save state information, delete temporary files, or restore
437 the previous terminal modes. Such a handler should end by specifying
438 the default action for the signal that happened and then reraising it;
439 this will cause the program to terminate with that signal, as if it had
440 not had a handler. (@xref{Termination in Handler}.)
442 The (obvious) default action for all of these signals is to cause the
443 process to terminate.
447 @deftypevr Macro int SIGHUP
448 @cindex hangup signal
449 The @code{SIGHUP} (``hang-up'') signal is used to report that the user's
450 terminal is disconnected, perhaps because a network or telephone
451 connection was broken. For more information about this, see @ref{Control
454 This signal is also used to report the termination of the controlling
455 process on a terminal to jobs associated with that session; this
456 termination effectively disconnects all processes in the session from
457 the controlling terminal. For more information, see @ref{Termination
463 @deftypevr Macro int SIGINT
464 @cindex interrupt signal
465 The @code{SIGINT} (``program interrupt'') signal is sent when the user
466 types the INTR character (normally @kbd{C-c}). @xref{Special
467 Characters}, for information about terminal driver support for
473 @deftypevr Macro int SIGQUIT
476 The @code{SIGQUIT} signal is similar to @code{SIGINT}, except that it's
477 controlled by a different key---the QUIT character, usually
478 @kbd{C-\}---and produces a core dump when it terminates the process,
479 just like a program error signal. You can think of this as a
480 program error condition ``detected'' by the user.
482 @xref{Program Error Signals}, for information about core dumps.
483 @xref{Special Characters}, for information about terminal driver
486 Certain kinds of cleanups are best omitted in handling @code{SIGQUIT}.
487 For example, if the program creates temporary files, it should handle
488 the other termination requests by deleting the temporary files. But it
489 is better for @code{SIGQUIT} not to delete them, so that the user can
490 examine them in conjunction with the core dump.
495 @deftypevr Macro int SIGTERM
496 @cindex termination signal
497 The @code{SIGTERM} signal is a generic signal used to cause program
498 termination. Unlike @code{SIGKILL}, this signal can be blocked,
499 handled, and ignored.
501 The shell command @code{kill} generates @code{SIGTERM} by default.
507 @deftypevr Macro int SIGKILL
508 The @code{SIGKILL} signal is used to cause immediate program termination.
509 It cannot be handled or ignored, and is therefore always fatal. It is
510 also not possible to block this signal.
512 This signal is generated only by explicit request. Since it cannot be
513 handled, you should generate it only as a last resort, after first
514 trying a less drastic method such as @kbd{C-c} or @code{SIGTERM}. If a
515 process does not respond to any other termination signals, sending it a
516 @code{SIGKILL} signal will almost always cause it to go away.
518 In fact, if @code{SIGKILL} fails to terminate a process, that by itself
519 constitutes an operating system bug which you should report.
524 @subsection Alarm Signals
526 These signals are used to indicate the expiration of timers.
527 @xref{Setting an Alarm}, for information about functions that cause
528 these signals to be sent.
530 The default behavior for these signals is to cause program termination.
531 This default is rarely useful, but no other default would be useful;
532 most of the ways of using these signals would require handler functions
537 @deftypevr Macro int SIGALRM
538 This signal typically indicates expiration of a timer that measures real
539 or clock time. It is used by the @code{alarm} function, for example.
545 @deftypevr Macro int SIGVTALRM
546 This signal typically indicates expiration of a timer that measures CPU
547 time used by the current process. The name is an abbreviation for
548 ``virtual time alarm''.
550 @cindex virtual time alarm signal
554 @deftypevr Macro int SIGPROF
555 This signal is typically indicates expiration of a timer that measures
556 both CPU time used by the current process, and CPU time expended on
557 behalf of the process by the system. Such a timer is used to implement
558 code profiling facilities, hence the name of this signal.
560 @cindex profiling alarm signal
563 @node Asynchronous I/O Signals
564 @subsection Asynchronous I/O Signals
566 The signals listed in this section are used in conjunction with
567 asynchronous I/O facilities. You have to take explicit action by
568 calling @code{fcntl} to enable a particular file descriptior to generate
569 these signals (@pxref{Interrupt Input}). The default action for these
570 signals is to ignore them.
574 @deftypevr Macro int SIGIO
575 @cindex input available signal
576 @cindex output possible signal
577 This signal is sent when a file descriptor is ready to perform input
580 On most operating systems, terminals and sockets are the only kinds of
581 files that can generate @code{SIGIO}; other kinds, including ordinary
582 files, never generate @code{SIGIO} even if you ask them to.
587 @deftypevr Macro int SIGURG
588 @cindex urgent data signal
589 This signal is sent when ``urgent'' or out-of-band data arrives on a
590 socket. @xref{Out-of-Band Data}.
593 @node Job Control Signals
594 @subsection Job Control Signals
595 @cindex job control signals
597 These signals are used to support job control. If your system
598 doesn't support job control, then these macros are defined but the
599 signals themselves can't be raised or handled.
601 You should generally leave these signals alone unless you really
602 understand how job control works. @xref{Job Control}.
606 @deftypevr Macro int SIGCHLD
607 @cindex child process signal
608 This signal is sent to a parent process whenever one of its child
609 processes terminates or stops.
611 The default action for this signal is to ignore it. If you establish a
612 handler for this signal while there are child processes that have
613 terminated but not reported their status via @code{wait} or
614 @code{waitpid} (@pxref{Process Completion}), whether your new handler
615 applies to those processes or not depends on the particular operating
621 @deftypevr Macro int SIGCONT
622 @cindex continue signal
623 You can send a @code{SIGCONT} signal to a process to make it continue.
624 The default behavior for this signal is to make the process continue if
625 it is stopped, and to ignore it otherwise.
627 Most programs have no reason to handle @code{SIGCONT}; they simply
628 resume execution without realizing they were ever stopped. You can use
629 a handler for @code{SIGCONT} to make a program do something special when
630 it is stopped and continued---for example, to reprint a prompt when it
631 is suspended while waiting for input.
636 @deftypevr Macro int SIGSTOP
637 The @code{SIGSTOP} signal stops the process. It cannot be handled,
644 @deftypevr Macro int SIGTSTP
645 The @code{SIGTSTP} signal is an interactive stop signal. Unlike
646 @code{SIGSTOP}, this signal can be handled and ignored.
648 Your program should handle this signal if you have a special need to
649 leave files or system tables in a secure state when a process is
650 stopped. For example, programs that turn off echoing should handle
651 @code{SIGTSTP} so they can turn echoing back on before stopping.
653 This signal is generated when the user types the SUSP character
654 (normally @kbd{C-z}). For more information about terminal driver
655 support, see @ref{Special Characters}.
657 @cindex interactive stop signal
661 @deftypevr Macro int SIGTTIN
662 A process cannot read from the the user's terminal while it is running
663 as a background job. When any process in a background job tries to
664 read from the terminal, all of the processes in the job are sent a
665 @code{SIGTTIN} signal. The default action for this signal is to
666 stop the process. For more information about how this interacts with
667 the terminal driver, see @ref{Access to the Terminal}.
669 @cindex terminal input signal
673 @deftypevr Macro int SIGTTOU
674 This is similar to @code{SIGTTIN}, but is generated when a process in a
675 background job attempts to write to the terminal or set its modes.
676 Again, the default action is to stop the process.
678 @cindex terminal output signal
680 While a process is stopped, no more signals can be delivered to it until
681 it is continued, except @code{SIGKILL} signals and (obviously)
682 @code{SIGCONT} signals. The @code{SIGKILL} signal always causes
683 termination of the process and can't be blocked or ignored. You can
684 block or ignore @code{SIGCONT}, but it always causes the process to
685 be continued anyway if it is stopped. Sending a @code{SIGCONT} signal
686 to a process causes any pending stop signals for that process to be
687 discarded. Likewise, any pending @code{SIGCONT} signals for a process
688 are discarded when it receives a stop signal.
690 When a process in an orphaned process group (@pxref{Orphaned Process
691 Groups}) receives a @code{SIGTSTP}, @code{SIGTTIN}, or @code{SIGTTOU}
692 signal and does not handle it, the process does not stop. Stopping the
693 process would be unreasonable since there would be no way to continue
694 it. What happens instead depends on the operating system you are
695 using. Some systems may do nothing; others may deliver another signal
696 instead, such as @code{SIGKILL} or @code{SIGHUP}.
699 On the GNU system, it is possible to reattach to the orphaned process
700 group and continue it, so stop signals do stop the process as usual on
701 a GNU system unless you have requested POSIX compatibility ``till it
705 @node Miscellaneous Signals
706 @subsection Miscellaneous Signals
708 These signals are used to report various other conditions. The default
709 action for all of them is to cause the process to terminate.
713 @deftypevr Macro int SIGPIPE
715 @cindex broken pipe signal
716 If you use pipes or FIFOs, you have to design your application so that
717 one process opens the pipe for reading before another starts writing.
718 If the reading process never starts, or terminates unexpectedly, writing
719 to the pipe or FIFO raises a @code{SIGPIPE} signal. If @code{SIGPIPE}
720 is blocked, handled or ignored, the offending call fails with
721 @code{EPIPE} instead.
723 Pipes and FIFO special files are discussed in more detail in @ref{Pipes
726 Another cause of @code{SIGPIPE} is when you try to output to a socket
727 that isn't connected. @xref{Sending Data}.
733 @deftypevr Macro int SIGUSR1
737 @deftypevr Macro int SIGUSR2
738 The @code{SIGUSR1} and @code{SIGUSR2} signals are set aside for you to
739 use any way you want. They're useful for interprocess communication.
740 Since these signals are normally fatal, you should write a signal handler
741 for them in the program that receives the signal.
743 There is an example showing the use of @code{SIGUSR1} and @code{SIGUSR2}
744 in @ref{Signaling Another Process}.
748 @node Nonstandard Signals
749 @subsection Nonstandard Signals
751 Particular operating systems support additional signals not listed
752 above. The ANSI C standard reserves all identifiers beginning with
753 @samp{SIG} followed by an uppercase letter for the names of signals.
754 You should consult the documentation or header files for your particular
755 operating system and processor type to find out about the specific
758 For example, some systems support extra signals which correspond to
759 hardware traps. Some other kinds of signals commonly supported are used
760 to implement limits on CPU time or file system usage, asynchronous
761 changes to terminal configuration, and the like. Systems may also
762 define signal names that are aliases for standard signal names.
764 You can generally assume that the default action (or the action set up
765 by the shell) for implementation-defined signals is reasonable, and not
766 worry about them yourself. In fact, it's usually a bad idea to ignore
767 or block signals you don't know anything about, or try to establish a
768 handler for signals whose meanings you don't know.
770 Here are some of the other signals found on commonly used operating
775 Obsolete name for @code{SIGCHLD}.
778 Generated by the machine's breakpoint instruction. Used by debuggers.
779 Default action is to dump core.
782 Generated by the PDP-11 ``iot'' instruction; equivalent to @code{SIGABRT}.
783 Default action is to dump core.
786 Emulator trap; this results from certain unimplemented instructions.
787 It is a program error signal.
790 Bad system call; that is to say, the instruction to trap to the
791 operating system was executed, but the code number for the system call
792 to perform was invalid. This is a program error signal.
795 This is a System V signal name, more or less similar to @code{SIGIO}.
798 CPU time limit exceeded. This is used for batch processing.
799 Default action is program termination.
802 File size limit exceeded. This is used for batch processing.
803 Default action is program termination.
806 Window size change. This is generated on certain systems when the size
807 of the current window on the screen is changed. Default action is to
812 @node Signal Messages
813 @subsection Signal Messages
814 @cindex signal messages
816 We mentioned above that the shell prints a message describing the signal
817 that terminated a child process. The clean way to print a message
818 describing a signal is to use the functions @code{strsignal} and
819 @code{psignal}. These functions use a signal number to specify which
820 kind of signal to describe. The signal number may come from the
821 termination status of a child process (@pxref{Process Completion}) or it
822 may come from a signal handler in the same process.
826 @deftypefun {char *} strsignal (int @var{signum})
827 This function returns a pointer to a statically-allocated string
828 containing a message describing the signal @var{signum}. You
829 should not modify the contents of this string; and, since it can be
830 rewritten on subsequent calls, you should save a copy of it if you need
831 to reference it later.
834 This function is a GNU extension, declared in the header file
840 @deftypefun void psignal (int @var{signum}, const char *@var{message})
841 This function prints a message describing the signal @var{signum} to the
842 standard error output stream @code{stderr}; see @ref{Standard Streams}.
844 If you call @code{psignal} with a @var{message} that is either a null
845 pointer or an empty string, @code{psignal} just prints the message
846 corresponding to @var{signum}, adding a trailing newline.
848 If you supply a non-null @var{message} argument, then @code{psignal}
849 prefixes its output with this string. It adds a colon and a space
850 character to separate the @var{message} from the string corresponding
854 This function is a BSD feature, declared in the header file @file{stdio.h}.
858 There is also an array @code{sys_siglist} which contains the messages
859 for the various signal codes. This array exists on BSD systems, unlike
863 @section Specifying Signal Actions
864 @cindex signal actions
865 @cindex establishing a handler
867 The simplest way to change the action for a signal is to use the
868 @code{signal} function. You can specify a built-in action (such as to
869 ignore the signal), or you can @dfn{establish a handler}.
871 The GNU library also implements the more versatile @code{sigaction}
872 facility. This section describes both facilities and gives suggestions
873 on which to use when.
876 * Basic Signal Handling:: The simple @code{signal} function.
877 * Advanced Signal Handling:: The more powerful @code{sigaction} function.
878 * Signal and Sigaction:: How those two functions interact.
879 * Sigaction Function Example:: An example of using the sigaction function.
880 * Flags for Sigaction:: Specifying options for signal handling.
881 * Initial Signal Actions:: How programs inherit signal actions.
884 @node Basic Signal Handling
885 @subsection Basic Signal Handling
886 @cindex @code{signal} function
888 The @code{signal} function provides a simple interface for establishing
889 an action for a particular signal. The function and associated macros
890 are declared in the header file @file{signal.h}.
895 @deftp {Data Type} sighandler_t
896 This is the type of signal handler functions. Signal handlers take one
897 integer argument specifying the signal number, and have return type
898 @code{void}. So, you should define handler functions like this:
901 void @var{handler} (int @code{signum}) @{ @dots{} @}
904 The name @code{sighandler_t} for this data type is a GNU extension.
909 @deftypefun sighandler_t signal (int @var{signum}, sighandler_t @var{action})
910 The @code{signal} function establishes @var{action} as the action for
911 the signal @var{signum}.
913 The first argument, @var{signum}, identifies the signal whose behavior
914 you want to control, and should be a signal number. The proper way to
915 specify a signal number is with one of the symbolic signal names
916 described in @ref{Standard Signals}---don't use an explicit number, because
917 the numerical code for a given kind of signal may vary from operating
918 system to operating system.
920 The second argument, @var{action}, specifies the action to use for the
921 signal @var{signum}. This can be one of the following:
926 @cindex default action for a signal
927 @code{SIG_DFL} specifies the default action for the particular signal.
928 The default actions for various kinds of signals are stated in
929 @ref{Standard Signals}.
933 @cindex ignore action for a signal
934 @code{SIG_IGN} specifies that the signal should be ignored.
936 Your program generally should not ignore signals that represent serious
937 events or that are normally used to request termination. You cannot
938 ignore the @code{SIGKILL} or @code{SIGSTOP} signals at all. You can
939 ignore program error signals like @code{SIGSEGV}, but ignoring the error
940 won't enable the program to continue executing meaningfully. Ignoring
941 user requests such as @code{SIGINT}, @code{SIGQUIT}, and @code{SIGTSTP}
944 When you do not wish signals to be delivered during a certain part of
945 the program, the thing to do is to block them, not ignore them.
946 @xref{Blocking Signals}.
949 Supply the address of a handler function in your program, to specify
950 running this handler as the way to deliver the signal.
952 For more information about defining signal handler functions,
953 see @ref{Defining Handlers}.
956 If you set the action for a signal to @code{SIG_IGN}, or if you set it
957 to @code{SIG_DFL} and the default action is to ignore that signal, then
958 any pending signals of that type are discarded (even if they are
959 blocked). Discarding the pending signals means that they will never be
960 delivered, not even if you subsequently specify another action and
961 unblock this kind of signal.
963 The @code{signal} function returns the action that was previously in
964 effect for the specified @var{signum}. You can save this value and
965 restore it later by calling @code{signal} again.
967 If @code{signal} can't honor the request, it returns @code{SIG_ERR}
968 instead. The following @code{errno} error conditions are defined for
973 You specified an invalid @var{signum}; or you tried to ignore or provide
974 a handler for @code{SIGKILL} or @code{SIGSTOP}.
978 Here is a simple example of setting up a handler to delete temporary
979 files when certain fatal signals happen:
985 termination_handler (int signum)
989 for (p = temp_file_list; p; p = p->next)
997 if (signal (SIGINT, termination_handler) == SIG_IGN)
998 signal (SIGINT, SIG_IGN);
999 if (signal (SIGHUP, termination_handler) == SIG_IGN)
1000 signal (SIGHUP, SIG_IGN);
1001 if (signal (SIGTERM, termination_handler) == SIG_IGN)
1002 signal (SIGTERM, SIG_IGN);
1008 Note how if a given signal was previously set to be ignored, this code
1009 avoids altering that setting. This is because non-job-control shells
1010 often ignore certain signals when starting children, and it is important
1011 for the children to respect this.
1013 We do not handle @code{SIGQUIT} or the program error signals in this
1014 example because these are designed to provide information for debugging
1015 (a core dump), and the temporary files may give useful information.
1019 @deftypefun sighandler_t ssignal (int @var{signum}, sighandler_t @var{action})
1020 The @code{ssignal} function does the same thing as @code{signal}; it is
1021 provided only for compatibility with SVID.
1026 @deftypevr Macro sighandler_t SIG_ERR
1027 The value of this macro is used as the return value from @code{signal}
1028 to indicate an error.
1032 @comment RMS says that ``we don't do this''.
1033 Implementations might define additional macros for built-in signal
1034 actions that are suitable as a @var{action} argument to @code{signal},
1035 besides @code{SIG_IGN} and @code{SIG_DFL}. Identifiers whose names
1036 begin with @samp{SIG_} followed by an uppercase letter are reserved for
1041 @node Advanced Signal Handling
1042 @subsection Advanced Signal Handling
1043 @cindex @code{sigaction} function
1045 The @code{sigaction} function has the same basic effect as
1046 @code{signal}: to specify how a signal should be handled by the process.
1047 However, @code{sigaction} offers more control, at the expense of more
1048 complexity. In particular, @code{sigaction} allows you to specify
1049 additional flags to control when the signal is generated and how the
1052 The @code{sigaction} function is declared in @file{signal.h}.
1057 @deftp {Data Type} {struct sigaction}
1058 Structures of type @code{struct sigaction} are used in the
1059 @code{sigaction} function to specify all the information about how to
1060 handle a particular signal. This structure contains at least the
1064 @item sighandler_t sa_handler
1065 This is used in the same way as the @var{action} argument to the
1066 @code{signal} function. The value can be @code{SIG_DFL},
1067 @code{SIG_IGN}, or a function pointer. @xref{Basic Signal Handling}.
1069 @item sigset_t sa_mask
1070 This specifies a set of signals to be blocked while the handler runs.
1071 Blocking is explained in @ref{Blocking for Handler}. Note that the
1072 signal that was delivered is automatically blocked by default before its
1073 handler is started; this is true regardless of the value in
1074 @code{sa_mask}. If you want that signal not to be blocked within its
1075 handler, you must write code in the handler to unblock it.
1078 This specifies various flags which can affect the behavior of
1079 the signal. These are described in more detail in @ref{Flags for Sigaction}.
1085 @deftypefun int sigaction (int @var{signum}, const struct sigaction *@var{action}, struct sigaction *@var{old_action})
1086 The @var{action} argument is used to set up a new action for the signal
1087 @var{signum}, while the @var{old_action} argument is used to return
1088 information about the action previously associated with this symbol.
1089 (In other words, @var{old_action} has the same purpose as the
1090 @code{signal} function's return value---you can check to see what the
1091 old action in effect for the signal was, and restore it later if you
1094 Either @var{action} or @var{old_action} can be a null pointer. If
1095 @var{old_action} is a null pointer, this simply suppresses the return
1096 of information about the old action. If @var{action} is a null pointer,
1097 the action associated with the signal @var{signum} is unchanged; this
1098 allows you to inquire about how a signal is being handled without changing
1101 The return value from @code{sigaction} is zero if it succeeds, and
1102 @code{-1} on failure. The following @code{errno} error conditions are
1103 defined for this function:
1107 The @var{signum} argument is not valid, or you are trying to
1108 trap or ignore @code{SIGKILL} or @code{SIGSTOP}.
1112 @node Signal and Sigaction
1113 @subsection Interaction of @code{signal} and @code{sigaction}
1115 It's possible to use both the @code{signal} and @code{sigaction}
1116 functions within a single program, but you have to be careful because
1117 they can interact in slightly strange ways.
1119 The @code{sigaction} function specifies more information than the
1120 @code{signal} function, so the return value from @code{signal} cannot
1121 express the full range of @code{sigaction} possibilities. Therefore, if
1122 you use @code{signal} to save and later reestablish an action, it may
1123 not be able to reestablish properly a handler that was established with
1126 To avoid having problems as a result, always use @code{sigaction} to
1127 save and restore a handler if your program uses @code{sigaction} at all.
1128 Since @code{sigaction} is more general, it can properly save and
1129 reestablish any action, regardless of whether it was established
1130 originally with @code{signal} or @code{sigaction}.
1132 If you establish an action with @code{signal} and then examine it with
1133 @code{sigaction}, the handler address that you get may not be the same
1134 as what you specified with @code{signal}. It may not even be suitable
1135 for use as an action argument with @code{signal}. But you can rely on
1136 using it as an argument to @code{sigaction}.
1138 So, you're better off using one or the other of the mechanisms
1139 consistently within a single program.
1141 @strong{Portability Note:} The basic @code{signal} function is a feature
1142 of ANSI C, while @code{sigaction} is part of the POSIX.1 standard. If
1143 you are concerned about portability to non-POSIX systems, then you
1144 should use the @code{signal} function instead.
1146 @node Sigaction Function Example
1147 @subsection @code{sigaction} Function Example
1149 In @ref{Basic Signal Handling}, we gave an example of establishing a
1150 simple handler for termination signals using @code{signal}. Here is an
1151 equivalent example using @code{sigaction}:
1157 termination_handler (int signum)
1159 struct temp_file *p;
1161 for (p = temp_file_list; p; p = p->next)
1169 struct sigaction new_action, old_action;
1171 /* @r{Set up the structure to specify the new action.} */
1172 new_action.sa_handler = termination_handler;
1173 sigemptyset (&new_action.sa_mask);
1174 new_action.sa_flags = 0;
1176 sigaction (SIGINT, NULL, &old_action);
1177 if (old_action.sa_handler != SIG_IGN)
1178 sigaction (SIGINT, &new_action, NULL);
1179 sigaction (SIGHUP, NULL, &old_action);
1180 if (old_action.sa_handler != SIG_IGN)
1181 sigaction (SIGHUP, &new_action, NULL);
1182 sigaction (SIGTERM, NULL, &old_action);
1183 if (old_action.sa_handler != SIG_IGN)
1184 sigaction (SIGTERM, &new_action, NULL);
1189 The program just loads the @code{new_action} structure with the desired
1190 parameters and passes it in the @code{sigaction} call. The usage of
1191 @code{sigemptyset} is described later; see @ref{Blocking Signals}.
1193 As in the example using @code{signal}, we avoid handling signals
1194 previously set to be ignored. Here we can avoid altering the signal
1195 handler even momentarily, by using the feature of @code{sigaction} that
1196 lets us examine the current action without specifying a new one.
1198 Here is another example. It retrieves information about the current
1199 action for @code{SIGINT} without changing that action.
1202 struct sigaction query_action;
1204 if (sigaction (SIGINT, NULL, &query_action) < 0)
1205 /* @r{@code{sigaction} returns -1 in case of error.} */
1206 else if (query_action.sa_handler == SIG_DFL)
1207 /* @r{@code{SIGINT} is handled in the default, fatal manner.} */
1208 else if (query_action.sa_handler == SIG_IGN)
1209 /* @r{@code{SIGINT} is ignored.} */
1211 /* @r{A programmer-defined signal handler is in effect.} */
1214 @node Flags for Sigaction
1215 @subsection Flags for @code{sigaction}
1216 @cindex signal flags
1217 @cindex flags for @code{sigaction}
1218 @cindex @code{sigaction} flags
1220 The @code{sa_flags} member of the @code{sigaction} structure is a
1221 catch-all for special features. Most of the time, @code{SA_RESTART} is
1222 a good value to use for this field.
1224 The value of @code{sa_flags} is interpreted as a bit mask. Thus, you
1225 should choose the flags you want to set, @sc{or} those flags together,
1226 and store the result in the @code{sa_flags} member of your
1227 @code{sigaction} structure.
1229 Each signal number has its own set of flags. Each call to
1230 @code{sigaction} affects one particular signal number, and the flags
1231 that you specify apply only to that particular signal.
1233 In the GNU C library, establishing a handler with @code{signal} sets all
1234 the flags to zero except for @code{SA_RESTART}, whose value depends on
1235 the settings you have made with @code{siginterrupt}. @xref{Interrupted
1236 Primitives}, to see what this is about.
1239 These macros are defined in the header file @file{signal.h}.
1243 @deftypevr Macro int SA_NOCLDSTOP
1244 This flag is meaningful only for the @code{SIGCHLD} signal. When the
1245 flag is set, the system delivers the signal for a terminated child
1246 process but not for one that is stopped. By default, @code{SIGCHLD} is
1247 delivered for both terminated children and stopped children.
1249 Setting this flag for a signal other than @code{SIGCHLD} has no effect.
1254 @deftypevr Macro int SA_ONSTACK
1255 If this flag is set for a particular signal number, the system uses the
1256 signal stack when delivering that kind of signal. @xref{BSD Signal
1262 @deftypevr Macro int SA_RESTART
1263 This flag controls what happens when a signal is delivered during
1264 certain primitives (such as @code{open}, @code{read} or @code{write}),
1265 and the signal handler returns normally. There are two alternatives:
1266 the library function can resume, or it can return failure with error
1269 The choice is controlled by the @code{SA_RESTART} flag for the
1270 particular kind of signal that was delivered. If the flag is set,
1271 returning from a handler resumes the library function. If the flag is
1272 clear, returning from a handler makes the function fail.
1273 @xref{Interrupted Primitives}.
1276 @node Initial Signal Actions
1277 @subsection Initial Signal Actions
1278 @cindex initial signal actions
1280 When a new process is created (@pxref{Creating a Process}), it inherits
1281 handling of signals from its parent process. However, when you load a
1282 new process image using the @code{exec} function (@pxref{Executing a
1283 File}), any signals that you've defined your own handlers for revert to
1284 their @code{SIG_DFL} handling. (If you think about it a little, this
1285 makes sense; the handler functions from the old program are specific to
1286 that program, and aren't even present in the address space of the new
1287 program image.) Of course, the new program can establish its own
1290 When a program is run by a shell, the shell normally sets the initial
1291 actions for the child process to @code{SIG_DFL} or @code{SIG_IGN}, as
1292 appropriate. It's a good idea to check to make sure that the shell has
1293 not set up an initial action of @code{SIG_IGN} before you establish your
1294 own signal handlers.
1296 Here is an example of how to establish a handler for @code{SIGHUP}, but
1297 not if @code{SIGHUP} is currently ignored:
1302 struct sigaction temp;
1304 sigaction (SIGHUP, NULL, &temp);
1306 if (temp.sa_handler != SIG_IGN)
1308 temp.sa_handler = handle_sighup;
1309 sigemptyset (&temp.sa_mask);
1310 sigaction (SIGHUP, &temp, NULL);
1315 @node Defining Handlers
1316 @section Defining Signal Handlers
1317 @cindex signal handler function
1319 This section describes how to write a signal handler function that can
1320 be established with the @code{signal} or @code{sigaction} functions.
1322 A signal handler is just a function that you compile together with the
1323 rest of the program. Instead of directly invoking the function, you use
1324 @code{signal} or @code{sigaction} to tell the operating system to call
1325 it when a signal arrives. This is known as @dfn{establishing} the
1326 handler. @xref{Signal Actions}.
1328 There are two basic strategies you can use in signal handler functions:
1332 You can have the handler function note that the signal arrived by
1333 tweaking some global data structures, and then return normally.
1336 You can have the handler function terminate the program or transfer
1337 control to a point where it can recover from the situation that caused
1341 You need to take special care in writing handler functions because they
1342 can be called asynchronously. That is, a handler might be called at any
1343 point in the program, unpredictably. If two signals arrive during a
1344 very short interval, one handler can run within another. This section
1345 describes what your handler should do, and what you should avoid.
1348 * Handler Returns:: Handlers that return normally, and what
1350 * Termination in Handler:: How handler functions terminate a program.
1351 * Longjmp in Handler:: Nonlocal transfer of control out of a
1353 * Signals in Handler:: What happens when signals arrive while
1354 the handler is already occupied.
1355 * Merged Signals:: When a second signal arrives before the
1357 * Nonreentrancy:: Do not call any functions unless you know they
1358 are reentrant with respect to signals.
1359 * Atomic Data Access:: A single handler can run in the middle of
1360 reading or writing a single object.
1363 @node Handler Returns
1364 @subsection Signal Handlers That Return
1366 Handlers which return normally are usually used for signals such as
1367 @code{SIGALRM} and the I/O and interprocess communication signals. But
1368 a handler for @code{SIGINT} might also return normally after setting a
1369 flag that tells the program to exit at a convenient time.
1371 It is not safe to return normally from the handler for a program error
1372 signal, because the behavior of the program when the handler function
1373 returns is not defined after a program error. @xref{Program Error
1376 Handlers that return normally must modify some global variable in order
1377 to have any effect. Typically, the variable is one that is examined
1378 periodically by the program during normal operation. Its data type
1379 should be @code{sig_atomic_t} for reasons described in @ref{Atomic
1382 Here is a simple example of such a program. It executes the body of
1383 the loop until it has noticed that a @code{SIGALRM} signal has arrived.
1384 This technique is useful because it allows the iteration in progress
1385 when the signal arrives to complete before the loop exits.
1388 @include sigh1.c.texi
1391 @node Termination in Handler
1392 @subsection Handlers That Terminate the Process
1394 Handler functions that terminate the program are typically used to cause
1395 orderly cleanup or recovery from program error signals and interactive
1398 The cleanest way for a handler to terminate the process is to raise the
1399 same signal that ran the handler in the first place. Here is how to do
1403 volatile sig_atomic_t fatal_error_in_progress = 0;
1406 fatal_error_signal (int sig)
1409 /* @r{Since this handler is established for more than one kind of signal, }
1410 @r{it might still get invoked recursively by delivery of some other kind}
1411 @r{of signal. Use a static variable to keep track of that.} */
1412 if (fatal_error_in_progress)
1414 fatal_error_in_progress = 1;
1418 /* @r{Now do the clean up actions:}
1419 @r{- reset terminal modes}
1420 @r{- kill child processes}
1421 @r{- remove lock files} */
1426 /* @r{Now reraise the signal. Since the signal is blocked,}
1427 @r{it will receive its default handling, which is}
1428 @r{to terminate the process. We could just call}
1429 @r{@code{exit} or @code{abort}, but reraising the signal}
1430 @r{sets the return status from the process correctly.} */
1436 @node Longjmp in Handler
1437 @subsection Nonlocal Control Transfer in Handlers
1438 @cindex non-local exit, from signal handler
1440 You can do a nonlocal transfer of control out of a signal handler using
1441 the @code{setjmp} and @code{longjmp} facilities (@pxref{Non-Local
1444 When the handler does a nonlocal control transfer, the part of the
1445 program that was running will not continue. If this part of the program
1446 was in the middle of updating an important data structure, the data
1447 structure will remain inconsistent. Since the program does not
1448 terminate, the inconsistency is likely to be noticed later on.
1450 There are two ways to avoid this problem. One is to block the signal
1451 for the parts of the program that update important data structures.
1452 Blocking the signal delays its delivery until it is unblocked, once the
1453 critical updating is finished. @xref{Blocking Signals}.
1455 The other way to re-initialize the crucial data structures in the signal
1456 handler, or make their values consistent.
1458 Here is a rather schematic example showing the reinitialization of one
1466 jmp_buf return_to_top_level;
1468 volatile sig_atomic_t waiting_for_input;
1471 handle_sigint (int signum)
1473 /* @r{We may have been waiting for input when the signal arrived,}
1474 @r{but we are no longer waiting once we transfer control.} */
1475 waiting_for_input = 0;
1476 longjmp (return_to_top_level, 1);
1485 signal (SIGINT, sigint_handler);
1488 prepare_for_command ();
1489 if (setjmp (return_to_top_level) == 0)
1490 read_and_execute_command ();
1496 /* @r{Imagine this is a subroutine used by various commands.} */
1500 if (input_from_terminal) @{
1501 waiting_for_input = 1;
1503 waiting_for_input = 0;
1512 @node Signals in Handler
1513 @subsection Signals Arriving While a Handler Runs
1514 @cindex race conditions, relating to signals
1516 What happens if another signal arrives when your signal handler function
1519 When the handler for a particular signal is invoked, that signal is
1520 normally blocked until the handler returns. That means that if two
1521 signals of the same kind arrive close together, the second one will be
1522 held until the first has been handled. (The handler can explicitly
1523 unblock the signal using @code{sigprocmask}, if you want to allow more
1524 signals of this type to arrive; see @ref{Process Signal Mask}.)
1526 However, your handler can still be interrupted by delivery of another
1527 kind of signal. To avoid this, you can use the @code{sa_mask} member of
1528 the action structure passed to @code{sigaction} to explicitly specify
1529 which signals should be blocked while the signal handler runs. These
1530 signals are in addition to the signal for which the handler was invoked,
1531 and any other signals that are normally blocked by the process.
1532 @xref{Blocking for Handler}.
1534 @strong{Portability Note:} Always use @code{sigaction} to establish a
1535 handler for a signal that you expect to receive asynchronously, if you
1536 want your program to work properly on System V Unix. On this system,
1537 the handling of a signal whose handler was established with
1538 @code{signal} automatically sets the signal's action back to
1539 @code{SIG_DFL}, and the handler must re-establish itself each time it
1540 runs. This practice, while inconvenient, does work when signals cannot
1541 arrive in succession. However, if another signal can arrive right away,
1542 it may arrive before the handler can re-establish itself. Then the
1543 second signal would receive the default handling, which could terminate
1546 @node Merged Signals
1547 @subsection Signals Close Together Merge into One
1548 @cindex handling multiple signals
1549 @cindex successive signals
1550 @cindex merging of signals
1552 If multiple signals of the same type are delivered to your process
1553 before your signal handler has a chance to be invoked at all, the
1554 handler may only be invoked once, as if only a single signal had
1555 arrived. In effect, the signals merge into one. This situation can
1556 arise when the signal is blocked, or in a multiprocessing environment
1557 where the system is busy running some other processes while the signals
1558 are delivered. This means, for example, that you cannot reliably use a
1559 signal handler to count signals. The only distinction you can reliably
1560 make is whether at least one signal has arrived since a given time in
1563 Here is an example of a handler for @code{SIGCHLD} that compensates for
1564 the fact that the number of signals recieved may not equal the number of
1565 child processes generate them. It assumes that the program keeps track
1566 of all the child processes with a chain of structures as follows:
1571 struct process *next;
1572 /* @r{The process ID of this child.} */
1574 /* @r{The descriptor of the pipe or pseudo terminal}
1575 @r{on which output comes from this child.} */
1576 int input_descriptor;
1577 /* @r{Nonzero if this process has stopped or terminated.} */
1578 sig_atomic_t have_status;
1579 /* @r{The status of this child; 0 if running,}
1580 @r{otherwise a status value from @code{waitpid}.} */
1584 struct process *process_list;
1587 This example also uses a flag to indicate whether signals have arrived
1588 since some time in the past---whenever the program last cleared it to
1592 /* @r{Nonzero means some child's status has changed}
1593 @r{so look at @code{process_list} for the details.} */
1594 int process_status_change;
1597 Here is the handler itself:
1601 sigchld_handler (int signo)
1603 int old_errno = errno;
1610 /* @r{Keep asking for a status until we get a definitive result.} */
1614 pid = waitpid (WAIT_ANY, &w, WNOHANG | WUNTRACED);
1616 while (pid <= 0 && errno == EINTR);
1619 /* @r{A real failure means there are no more}
1620 @r{stopped or terminated child processes, so return.} */
1625 /* @r{Find the process that signaled us, and record its status.} */
1627 for (p = process_list; p; p = p->next)
1628 if (p->pid == pid) @{
1630 /* @r{Indicate that the @code{status} field}
1631 @r{has data to look at. We do this only after storing it.} */
1634 /* @r{If process has terminated, stop waiting for its output.} */
1635 if (WIFSIGNALED (w) || WIFEXITED (w))
1636 if (p->input_descriptor)
1637 FD_CLR (p->input_descriptor, &input_wait_mask);
1639 /* @r{The program should check this flag from time to time}
1640 @r{to see if there is any news in @code{process_list}.} */
1641 ++process_status_change;
1644 /* @r{Loop around to handle all the processes}
1645 @r{that have something to tell us.} */
1650 Here is the proper way to check the flag @code{process_status_change}:
1653 if (process_status_change) @{
1655 process_status_change = 0;
1656 for (p = process_list; p; p = p->next)
1657 if (p->have_status) @{
1658 @dots{} @r{Examine @code{p->status}} @dots{}
1664 It is vital to clear the flag before examining the list; otherwise, if a
1665 signal were delivered just before the clearing of the flag, and after
1666 the appropriate element of the process list had been checked, the status
1667 change would go unnoticed until the next signal arrived to set the flag
1668 again. You could, of course, avoid this problem by blocking the signal
1669 while scanning the list, but it is much more elegant to guarantee
1670 correctness by doing things in the right order.
1672 The loop which checks process status avoids examining @code{p->status}
1673 until it sees that status has been validly stored. This is to make sure
1674 that the status cannot change in the middle of accessing it. Once
1675 @code{p->have_status} is set, it means that the child process is stopped
1676 or terminated, and in either case, it cannot stop or terminate again
1677 until the program has taken notice. @xref{Atomic Usage}, for more
1678 information about coping with interruptions during accessings of a
1681 Here is another way you can test whether the handler has run since the
1682 last time you checked. This technique uses a counter which is never
1683 changed outside the handler. Instead of clearing the count, the program
1684 remembers the previous value and sees whether it has changed since the
1685 previous check. The advantage of this method is that different parts of
1686 the program can check independently, each part checking whether there
1687 has been a signal since that part last checked.
1690 sig_atomic_t process_status_change;
1692 sig_atomic_t last_process_status_change;
1696 sig_atomic_t prev = last_process_status_change;
1697 last_process_status_change = process_status_change;
1698 if (last_process_status_change != prev) @{
1700 for (p = process_list; p; p = p->next)
1701 if (p->have_status) @{
1702 @dots{} @r{Examine @code{p->status}} @dots{}
1709 @subsection Signal Handling and Nonreentrant Functions
1710 @cindex restrictions on signal handler functions
1712 Handler functions usually don't do very much. The best practice is to
1713 write a handler that does nothing but set an external variable that the
1714 program checks regularly, and leave all serious work to the program.
1715 This is best because the handler can be called at asynchronously, at
1716 unpredictable times---perhaps in the middle of a system call, or even
1717 between the beginning and the end of a C operator that requires multiple
1718 instructions. The data structures being manipulated might therefore be
1719 in an inconsistent state when the handler function is invoked. Even
1720 copying one @code{int} variable into another can take two instructions
1723 This means you have to be very careful about what you do in a signal
1728 @cindex @code{volatile} declarations
1729 If your handler needs to access any global variables from your program,
1730 declare those variables @code{volatile}. This tells the compiler that
1731 the value of the variable might change asynchronously, and inhibits
1732 certain optimizations that would be invalidated by such modifications.
1735 @cindex reentrant functions
1736 If you call a function in the handler, make sure it is @dfn{reentrant}
1737 with respect to signals, or else make sure that the signal cannot
1738 interrupt a call to a related function.
1741 A function can be non-reentrant if it uses memory that is not on the
1746 If a function uses a static variable or a global variable, or a
1747 dynamically-allocated object that it finds for itself, then it is
1748 non-reentrant and any two calls to the function can interfere.
1750 For example, suppose that the signal handler uses @code{gethostbyname}.
1751 This function returns its value in a static object, reusing the same
1752 object each time. If the signal happens to arrive during a call to
1753 @code{gethostbyname}, or even after one (while the program is still
1754 using the value), it will clobber the value that the program asked for.
1756 However, if the program does not use @code{gethostbyname} or any other
1757 function that returns information in the same object, or if it always
1758 blocks signals around each use, then you are safe.
1760 There are a large number of library functions that return values in a
1761 fixed object, always reusing the same object in this fashion, and all of
1762 them cause the same problem. The description of a function in this
1763 manual always mentions this behavior.
1766 If a function uses and modifies an object that you supply, then it is
1767 potentially non-reentrant; two calls can interfere if they use the same
1770 This case arises when you do I/O using streams. Suppose that the
1771 signal handler prints a message with @code{fprintf}. Suppose that the
1772 program was in the middle of an @code{fprintf} call using the same
1773 stream when the signal was delivered. Both the signal handler's message
1774 and the program's data could be corrupted, because both calls operate on
1775 the same data structure---the stream itself.
1777 However, if you know that the stream that the handler uses cannot
1778 possibly be used by the program at a time when signals can arrive, then
1779 you are safe. It is no problem if the program uses some other stream.
1782 On most systems, @code{malloc} and @code{free} are not reentrant,
1783 because they use a static data structure which records what memory
1784 blocks are free. As a result, no library functions that allocate or
1785 free memory are reentrant. This includes functions that allocate space
1788 The best way to avoid the need to allocate memory in a handler is to
1789 allocate in advance space for signal handlers to use.
1791 The best way to avoid freeing memory in a handler is to flag or record
1792 the objects to be freed, and have the program check from time to time
1793 whether anything is waiting to be freed. But this must be done with
1794 care, because placing an object on a chain is not atomic, and if it is
1795 interrupted by another signal handler that does the same thing, you
1796 could ``lose'' one of the objects.
1798 On the GNU system, @code{malloc} and @code{free} are safe to use in
1799 signal handlers because it blocks signals. As a result, the library
1800 functions that allocate space for a result are also safe in signal
1801 handlers. The obstack allocation functions are safe as long as you
1802 don't use the same obstack both inside and outside of a signal handler.
1804 The relocating allocation functions (@pxref{Relocating Allocator})
1805 are certainly not safe to use in a signal handler.
1808 Any function that modifies @code{errno} is non-reentrant, but you can
1809 correct for this: in the handler, save the original value of
1810 @code{errno} and restore it before returning normally. This prevents
1811 errors that occur within the signal handler from being confused with
1812 errors from system calls at the point the program is interrupted to run
1815 This technique is generally applicable; if you want to call in a handler
1816 a function that modifies a particular object in memory, you can make
1817 this safe by saving and restoring that object.
1820 Merely reading from a memory object is safe provided that you can deal
1821 with any of the values that might appear in the object at a time when
1822 the signal can be delivered. Keep in mind that assignment to some data
1823 types requires more than one instruction, which means that the handler
1824 could run ``in the middle of'' an assignment to the variable if its type
1825 is not atomic. @xref{Atomic Data Access}.
1828 Merely writing into a memory object is safe as long as a sudden change
1829 in the value, at any time when the handler might run, will not disturb
1833 @node Atomic Data Access
1834 @subsection Atomic Data Access and Signal Handling
1836 Whether the data in your application concerns atoms, or mere text, you
1837 have to be careful about the fact that access to a single datum is not
1838 necessarily @dfn{atomic}. This means that it can take more than one
1839 instruction to read or write a single object. In such cases, a signal
1840 handler can run in the middle of reading or writing the object.
1842 There are three ways you can cope with this problem. You can use data
1843 types that are always accessed atomically; you can carefully arrange
1844 that nothing untoward happens if an access is interrupted, or you can
1845 block all signals around any access that had better not be interrupted
1846 (@pxref{Blocking Signals}).
1849 * Non-atomic Example:: A program illustrating interrupted access.
1850 * Types: Atomic Types. Data types that guarantee no interruption.
1851 * Usage: Atomic Usage. Proving that interruption is harmless.
1854 @node Non-atomic Example
1855 @subsubsection Example of Problems with Non-Atomic Access
1857 Here is an example which shows what can happen if a signal handler runs
1858 in the middle of modifying a variable. (Interrupting the reading of a
1859 variable can also lead to paradoxical results, but here we only show
1866 struct two_words @{ int a, b; @} memory;
1871 printf ("%d,%d\n", memory.a, memory.b);
1879 static struct two_words zeros = @{ 0, 0 @}, ones = @{ 1, 1 @};
1880 signal (SIGALRM, handler);
1892 This program fills @code{memory} with zeros, ones, zeros, ones,
1893 alternating forever; meanwhile, once per second, the alarm signal handler
1894 prints the current contents. (Calling @code{printf} in the handler is
1895 safe in this program because it is certainly not being called outside
1896 the handler when the signal happens.)
1898 Clearly, this program can print a pair of zeros or a pair of ones. But
1899 that's not all it can do! On most machines, it takes several
1900 instructions to store a new value in @code{memory}, and the value is
1901 stored one word at a time. If the signal is delivered in between these
1902 instructions, the handler might find that @code{memory.a} is zero and
1903 @code{memory.b} is one (or vice versa).
1905 On some machines it may be possible to store a new value in
1906 @code{memory} with just one instruction that cannot be interrupted. On
1907 these machines, the handler will always print two zeros or two ones.
1910 @subsubsection Atomic Types
1912 To avoid uncertainty about interrupting access to a variable, you can
1913 use a particular data type for which access is always atomic:
1914 @code{sig_atomic_t}. Reading and writing this data type is guaranteed
1915 to happen in a single instruction, so there's no way for a handler to
1916 run ``in the middle'' of an access.
1918 The type @code{sig_atomic_t} is always an integer data type, but which
1919 one it is, and how many bits it contains, may vary from machine to
1924 @deftp {Data Type} sig_atomic_t
1925 This is an integer data type. Objects of this type are always accessed
1929 In practice, you can assume that @code{int} and other integer types no
1930 longer than @code{int} are atomic. You can also assume that pointer
1931 types are atomic; that is very convenient. Both of these are true on
1932 all of the machines that the GNU C library supports, and on all POSIX
1934 @c ??? This might fail on a 386 that uses 64-bit pointers.
1937 @subsubsection Atomic Usage Patterns
1939 Certain patterns of access avoid any problem even if an access is
1940 interrupted. For example, a flag which is set by the handler, and
1941 tested and cleared by the main program from time to time, is always safe
1942 even if access actually requires two instructions. To show that this is
1943 so, we must consider each access that could be interrupted, and show
1944 that there is no problem if it is interrupted.
1946 An interrupt in the middle of testing the flag is safe because either it's
1947 recognized to be nonzero, in which case the precise value doesn't
1948 matter, or it will be seen to be nonzero the next time it's tested.
1950 An interrupt in the middle of clearing the flag is no problem because
1951 either the value ends up zero, which is what happens if a signal comes
1952 in just before the flag is cleared, or the value ends up nonzero, and
1953 subsequent events occur as if the signal had come in just after the flag
1954 was cleared. As long as the code handles both of these cases properly,
1955 it can also handle a signal in the middle of clearing the flag. (This
1956 is an example of the sort of reasoning you need to do to figure out
1957 whether non-atomic usage is safe.)
1959 Sometimes you can insure uninterrupted access to one object by
1960 protecting its use with another object, perhaps one whose type
1961 guarantees atomicity. @xref{Merged Signals}, for an example.
1963 @node Interrupted Primitives
1964 @section Primitives Interrupted by Signals
1966 A signal can arrive and be handled while an I/O primitive such as
1967 @code{open} or @code{read} is waiting for an I/O device. If the signal
1968 handler returns, the system faces the question: what should happen next?
1970 POSIX specifies one approach: make the primitive fail right away. The
1971 error code for this kind of failure is @code{EINTR}. This is flexible,
1972 but usually inconvenient. Typically, POSIX applications that use signal
1973 handlers must check for @code{EINTR} after each library function that
1974 can return it, in order to try the call again. Often programmers forget
1975 to check, which is a common source of error.
1977 The GNU library provides a convenient way to retry a call after a
1978 temporary failure, with the macro @code{TEMP_FAILURE_RETRY}:
1982 @defmac TEMP_FAILURE_RETRY (@var{expression})
1983 This macro evaluates @var{expression} once. If it fails and reports
1984 error code @code{EINTR}, @code{TEMP_FAILURE_RETRY} evaluates it again,
1985 and over and over until the result is not a temporary failure.
1987 The value returned by @code{TEMP_FAILURE_RETRY} is whatever value
1988 @var{expression} produced.
1991 BSD avoids @code{EINTR} entirely and provides a more convenient
1992 approach: to restart the interrupted primitive, instead of making it
1993 fail. If you choose this approach, you need not be concerned with
1996 You can choose either approach with the GNU library. If you use
1997 @code{sigaction} to establish a signal handler, you can specify how that
1998 handler should behave. If you specify the @code{SA_RESTART} flag,
1999 return from that handler will resume a primitive; otherwise, return from
2000 that handler will cause @code{EINTR}. @xref{Flags for Sigaction}.
2002 Another way to specify the choice is with the @code{siginterrupt}
2003 function. @xref{POSIX vs BSD}.
2005 When you don't specify with @code{sigaction} or @code{siginterrupt} what
2006 a particular handler should do, it uses a default choice. The default
2007 choice in the GNU library depends on the feature test macros you have
2008 defined. If you define @code{_BSD_SOURCE} or @code{_GNU_SOURCE} before
2009 calling @code{signal}, the default is to resume primitives; otherwise,
2010 the default is to make them fail with @code{EINTR}. (The library
2011 contains alternate versions of the @code{signal} function, and the
2012 feature test macros determine which one you really call.) @xref{Feature
2015 The primitives affected by this issue are @code{close}, @code{fcntl}
2016 (operation @code{F_SETLK}), @code{open}, @code{read}, @code{recv},
2017 @code{recvfrom}, @code{select}, @code{send}, @code{sendto},
2018 @code{tcdrain}, @code{waitpid}, @code{wait}, and @code{write}.
2020 There is one situation where resumption never happens no matter which
2021 choice you make: when a data-transfer function such as @code{read} or
2022 @code{write} is interrupted by a signal after transferring part of the
2023 data. In this case, the function returns the number of bytes already
2024 transferred, indicating partial success.
2026 This might at first appear to cause unreliable behavior on
2027 record-oriented devices (including datagram sockets; @pxref{Datagrams}),
2028 where splitting one @code{read} or @code{write} into two would read or
2029 write two records. Actually, there is no problem, because interruption
2030 after a partial transfer cannot happen on such devices; they always
2031 transfer an entire record in one burst, with no waiting once data
2032 transfer has started.
2034 @node Generating Signals
2035 @section Generating Signals
2036 @cindex sending signals
2037 @cindex raising signals
2038 @cindex signals, generating
2040 Besides signals that are generated as a result of a hardware trap or
2041 interrupt, your program can explicitly send signals to itself or to
2045 * Signaling Yourself:: A process can send a signal to itself.
2046 * Signaling Another Process:: Send a signal to another process.
2047 * Permission for kill:: Permission for using @code{kill}.
2048 * Kill Example:: Using @code{kill} for Communication.
2051 @node Signaling Yourself
2052 @subsection Signaling Yourself
2054 A process can send itself a signal with the @code{raise} function. This
2055 function is declared in @file{signal.h}.
2060 @deftypefun int raise (int @var{signum})
2061 The @code{raise} function sends the signal @var{signum} to the calling
2062 process. It returns zero if successful and a nonzero value if it fails.
2063 About the only reason for failure would be if the value of @var{signum}
2069 @deftypefun int gsignal (int @var{signum})
2070 The @code{gsignal} function does the same thing as @code{raise}; it is
2071 provided only for compatibility with SVID.
2074 One convenient use for @code{raise} is to reproduce the default behavior
2075 of a signal that you have trapped. For instance, suppose a user of your
2076 program types the SUSP character (usually @kbd{C-z}; @pxref{Special
2077 Characters}) to send it an interactive stop stop signal
2078 (@code{SIGTSTP}), and you want to clean up some internal data buffers
2079 before stopping. You might set this up like this:
2081 @comment RMS suggested getting rid of the handler for SIGCONT in this function.
2082 @comment But that would require that the handler for SIGTSTP unblock the
2083 @comment signal before doing the call to raise. We haven't covered that
2084 @comment topic yet, and I don't want to distract from the main point of
2085 @comment the example with a digression to explain what is going on. As
2086 @comment the example is written, the signal that is raise'd will be delivered
2087 @comment as soon as the SIGTSTP handler returns, which is fine.
2092 /* @r{When a stop signal arrives, set the action back to the default
2093 and then resend the signal after doing cleanup actions.} */
2096 tstp_handler (int sig)
2098 signal (SIGTSTP, SIG_DFL);
2099 /* @r{Do cleanup actions here.} */
2104 /* @r{When the process is continued again, restore the signal handler.} */
2107 cont_handler (int sig)
2109 signal (SIGCONT, cont_handler);
2110 signal (SIGTSTP, tstp_handler);
2114 /* @r{Enable both handlers during program initialization.} */
2119 signal (SIGCONT, cont_handler);
2120 signal (SIGTSTP, tstp_handler);
2126 @strong{Portability note:} @code{raise} was invented by the ANSI C
2127 committee. Older systems may not support it, so using @code{kill} may
2128 be more portable. @xref{Signaling Another Process}.
2130 @node Signaling Another Process
2131 @subsection Signaling Another Process
2133 @cindex killing a process
2134 The @code{kill} function can be used to send a signal to another process.
2135 In spite of its name, it can be used for a lot of things other than
2136 causing a process to terminate. Some examples of situations where you
2137 might want to send signals between processes are:
2141 A parent process starts a child to perform a task---perhaps having the
2142 child running an infinite loop---and then terminates the child when the
2143 task is no longer needed.
2146 A process executes as part of a group, and needs to terminate or notify
2147 the other processes in the group when an error or other event occurs.
2150 Two processes need to synchronize while working together.
2153 This section assumes that you know a little bit about how processes
2154 work. For more information on this subject, see @ref{Child Processes}.
2156 The @code{kill} function is declared in @file{signal.h}.
2161 @deftypefun int kill (pid_t @var{pid}, int @var{signum})
2162 The @code{kill} function sends the signal @var{signum} to the process
2163 or process group specified by @var{pid}. Besides the signals listed in
2164 @ref{Standard Signals}, @var{signum} can also have a value of zero to
2165 check the validity of the @var{pid}.
2167 The @var{pid} specifies the process or process group to receive the
2172 The process whose identifier is @var{pid}.
2174 @item @var{pid} == 0
2175 All processes in the same process group as the sender. The sender
2176 itself does not receive the signal.
2178 @item @var{pid} < -1
2179 The process group whose identifier is @minus{}@var{pid}.
2181 @item @var{pid} == -1
2182 If the process is privileged, send the signal to all processes except
2183 for some special system processes. Otherwise, send the signal to all
2184 processes with the same effective user ID.
2187 A process can send a signal to itself with @w{@code{kill (getpid(),
2188 @var{signum});}}. If @code{kill} is used by a process to send a signal to
2189 itself, and the signal is not blocked, then @code{kill} delivers at
2190 least one signal (which might be some other pending unblocked signal
2191 instead of the signal @var{signum}) to that process before it returns.
2193 The return value from @code{kill} is zero if the signal can be sent
2194 successfully. Otherwise, no signal is sent, and a value of @code{-1} is
2195 returned. If @var{pid} specifies sending a signal to several processes,
2196 @code{kill} succeeds if it can send the signal to at least one of them.
2197 There's no way you can tell which of the processes got the signal
2198 or whether all of them did.
2200 The following @code{errno} error conditions are defined for this function:
2204 The @var{signum} argument is an invalid or unsupported number.
2207 You do not have the privilege to send a signal to the process or any of
2208 the processes in the process group named by @var{pid}.
2211 The @var{pid} argument does not refer to an existing process or group.
2217 @deftypefun int killpg (int @var{pgid}, int @var{signum})
2218 This is similar to @code{kill}, but sends signal @var{signum} to the
2219 process group @var{pgid}. This function is provided for compatibility
2220 with BSD; using @code{kill} to do this is more portable.
2223 As a simple example of @code{kill}, the call @w{@code{kill (getpid (),
2224 @var{sig})} has the same effect as @w{@code{raise (@var{sig})}}.
2226 @node Permission for kill
2227 @subsection Permission for using @code{kill}
2229 There are restrictions that prevent you from using @code{kill} to send
2230 signals to any random process. These are intended to prevent antisocial
2231 behavior such as arbitrarily killing off processes belonging to another
2232 user. In typical use, @code{kill} is used to pass signals between
2233 parent, child, and sibling processes, and in these situations you
2234 normally do have permission to send signals. The only common execption
2235 is when you run a setuid program in a child process; if the program
2236 changes its real UID as well as its effective UID, you may not have
2237 permission to send a signal. The @code{su} program does this.
2239 Whether a process has permission to send a signal to another process
2240 is determined by the user IDs of the two processes. This concept is
2241 discussed in detail in @ref{Process Persona}.
2243 Generally, for a process to be able to send a signal to another process,
2244 either the sending process must belong to a privileged user (like
2245 @samp{root}), or the real or effective user ID of the sending process
2246 must match the real or effective user ID of the receiving process. If
2247 the receiving process has changed its effective user ID from the
2248 set-user-ID mode bit on its process image file, then the owner of the
2249 process image file is used in place of its current effective user ID.
2250 In some implementations, a parent process might be able to send signals
2251 to a child process even if the user ID's don't match, and other
2252 implementations might enforce other restrictions.
2254 The @code{SIGCONT} signal is a special case. It can be sent if the
2255 sender is part of the same session as the receiver, regardless of
2259 @subsection Using @code{kill} for Communication
2260 @cindex interprocess communication, with signals
2261 Here is a longer example showing how signals can be used for
2262 interprocess communication. This is what the @code{SIGUSR1} and
2263 @code{SIGUSR2} signals are provided for. Since these signals are fatal
2264 by default, the process that is supposed to receive them must trap them
2265 through @code{signal} or @code{sigaction}.
2267 In this example, a parent process forks a child process and then waits
2268 for the child to complete its initialization. The child process tells
2269 the parent when it is ready by sending it a @code{SIGUSR1} signal, using
2270 the @code{kill} function.
2273 @include sigusr.c.texi
2276 This example uses a busy wait, which is bad, because it wastes CPU
2277 cycles that other programs could otherwise use. It is better to ask the
2278 system to wait until the signal arrives. See the example in
2279 @ref{Waiting for a Signal}.
2281 @node Blocking Signals
2282 @section Blocking Signals
2283 @cindex blocking signals
2285 Blocking a signal means telling the operating system to hold it and
2286 deliver it later. Generally, a program does not block signals
2287 indefinitely---it might as well ignore them by setting their actions to
2288 @code{SIG_IGN}. But it is useful to block signals briefly, to prevent
2289 them from interrupting sensitive operations. For instance:
2293 You can use the @code{sigprocmask} function to block signals while you
2294 modify global variables that are also modified by the handlers for these
2298 You can set @code{sa_mask} in your @code{sigaction} call to block
2299 certain signals while a particular signal handler runs. This way, the
2300 signal handler can run without being interrupted itself by signals.
2304 * Why Block:: The purpose of blocking signals.
2305 * Signal Sets:: How to specify which signals to
2307 * Process Signal Mask:: Blocking delivery of signals to your
2308 process during normal execution.
2309 * Testing for Delivery:: Blocking to Test for Delivery of
2311 * Blocking for Handler:: Blocking additional signals while a
2312 handler is being run.
2313 * Checking for Pending Signals:: Checking for Pending Signals
2314 * Remembering a Signal:: How you can get almost the same
2315 effect as blocking a signal, by
2316 handling it and setting a flag
2321 @subsection Why Blocking Signals is Useful
2323 Temporary blocking of signals with @code{sigprocmask} gives you a way to
2324 prevent interrupts during critical parts of your code. If signals
2325 arrive in that part of the program, they are delivered later, after you
2328 One example where this is useful is for sharing data between a signal
2329 handler and the rest of the program. If the type of the data is not
2330 @code{sig_atomic_t} (@pxref{Atomic Data Access}), then the signal
2331 handler could run when the rest of the program has only half finished
2332 reading or writing the data. This would lead to confusing consequences.
2334 To make the program reliable, you can prevent the signal handler from
2335 running while the rest of the program is examining or modifying that
2336 data---by blocking the appropriate signal around the parts of the
2337 program that touch the data.
2339 Blocking signals is also necessary when you want to perform a certain
2340 action only if a signal has not arrived. Suppose that the handler for
2341 the signal sets a flag of type @code{sig_atomic_t}; you would like to
2342 test the flag and perform the action if the flag is not set. This is
2343 unreliable. Suppose the signal is delivered immediately after you test
2344 the flag, but before the consequent action: then the program will
2345 perform the action even though the signal has arrived.
2347 The only way to test reliably for whether a signal has yet arrived is to
2348 test while the signal is blocked.
2351 @subsection Signal Sets
2353 All of the signal blocking functions use a data structure called a
2354 @dfn{signal set} to specify what signals are affected. Thus, every
2355 activity involves two stages: creating the signal set, and then passing
2356 it as an argument to a library function.
2359 These facilities are declared in the header file @file{signal.h}.
2364 @deftp {Data Type} sigset_t
2365 The @code{sigset_t} data type is used to represent a signal set.
2366 Internally, it may be implemented as either an integer or structure
2369 For portability, use only the functions described in this section to
2370 initialize, change, and retrieve information from @code{sigset_t}
2371 objects---don't try to manipulate them directly.
2374 There are two ways to initialize a signal set. You can initially
2375 specify it to be empty with @code{sigemptyset} and then add specified
2376 signals individually. Or you can specify it to be full with
2377 @code{sigfillset} and then delete specified signals individually.
2379 You must always initialize the signal set with one of these two
2380 functions before using it in any other way. Don't try to set all the
2381 signals explicitly because the @code{sigset_t} object might include some
2382 other information (like a version field) that needs to be initialized as
2383 well. (In addition, it's not wise to put into your program an
2384 assumption that the system has no signals aside from the ones you know
2389 @deftypefun int sigemptyset (sigset_t *@var{set})
2390 This function initializes the signal set @var{set} to exclude all of the
2391 defined signals. It always returns @code{0}.
2396 @deftypefun int sigfillset (sigset_t *@var{set})
2397 This function initializes the signal set @var{set} to include
2398 all of the defined signals. Again, the return value is @code{0}.
2403 @deftypefun int sigaddset (sigset_t *@var{set}, int @var{signum})
2404 This function adds the signal @var{signum} to the signal set @var{set}.
2405 All @code{sigaddset} does is modify @var{set}; it does not block or
2406 unblock any signals.
2408 The return value is @code{0} on success and @code{-1} on failure.
2409 The following @code{errno} error condition is defined for this function:
2413 The @var{signum} argument doesn't specify a valid signal.
2419 @deftypefun int sigdelset (sigset_t *@var{set}, int @var{signum})
2420 This function removes the signal @var{signum} from the signal set
2421 @var{set}. All @code{sigdelset} does is modify @var{set}; it does not
2422 block or unblock any signals. The return value and error conditions are
2423 the same as for @code{sigaddset}.
2426 Finally, there is a function to test what signals are in a signal set:
2430 @deftypefun int sigismember (const sigset_t *@var{set}, int @var{signum})
2431 The @code{sigismember} function tests whether the signal @var{signum} is
2432 a member of the signal set @var{set}. It returns @code{1} if the signal
2433 is in the set, @code{0} if not, and @code{-1} if there is an error.
2435 The following @code{errno} error condition is defined for this function:
2439 The @var{signum} argument doesn't specify a valid signal.
2443 @node Process Signal Mask
2444 @subsection Process Signal Mask
2446 @cindex process signal mask
2448 The collection of signals that are currently blocked is called the
2449 @dfn{signal mask}. Each process has its own signal mask. When you
2450 create a new process (@pxref{Creating a Process}), it inherits its
2451 parent's mask. You can block or unblock signals with total flexibility
2452 by modifying the signal mask.
2454 The prototype for the @code{sigprocmask} function is in @file{signal.h}.
2459 @deftypefun int sigprocmask (int @var{how}, const sigset_t *@var{set}, sigset_t *@var{oldset})
2460 The @code{sigprocmask} function is used to examine or change the calling
2461 process's signal mask. The @var{how} argument determines how the signal
2462 mask is changed, and must be one of the following values:
2469 Block the signals in @code{set}---add them to the existing mask. In
2470 other words, the new mask is the union of the existing mask and
2477 Unblock the signals in @var{set}---remove them from the existing mask.
2483 Use @var{set} for the mask; ignore the previous value of the mask.
2486 The last argument, @var{oldset}, is used to return information about the
2487 old process signal mask. If you just want to change the mask without
2488 looking at it, pass a null pointer as the @var{oldset} argument.
2489 Similarly, if you want to know what's in the mask without changing it,
2490 pass a null pointer for @var{set} (in this case the @var{how} argument
2491 is not significant). The @var{oldset} argument is often used to
2492 remember the previous signal mask in order to restore it later. (Since
2493 the signal mask is inherited over @code{fork} and @code{exec} calls, you
2494 can't predict what its contents are when your program starts running.)
2496 If invoking @code{sigprocmask} causes any pending signals to be
2497 unblocked, at least one of those signals is delivered to the process
2498 before @code{sigprocmask} returns. The order in which pending signals
2499 are delivered is not specified, but you can control the order explicitly
2500 by making multiple @code{sigprockmask} calls to unblock various signals
2503 The @code{sigprocmask} function returns @code{0} if successful, and @code{-1}
2504 to indicate an error. The following @code{errno} error conditions are
2505 defined for this function:
2509 The @var{how} argument is invalid.
2512 You can't block the @code{SIGKILL} and @code{SIGSTOP} signals, but
2513 if the signal set includes these, @code{sigprocmask} just ignores
2514 them instead of returning an error status.
2516 Remember, too, that blocking program error signals such as @code{SIGFPE}
2517 leads to undesirable results for signals generated by an actual program
2518 error (as opposed to signals sent with @code{raise} or @code{kill}).
2519 This is because your program may be too broken to be able to continue
2520 executing to a point where the signal is unblocked again.
2521 @xref{Program Error Signals}.
2524 @node Testing for Delivery
2525 @subsection Blocking to Test for Delivery of a Signal
2527 Now for a simple example. Suppose you establish a handler for
2528 @code{SIGALRM} signals that sets a flag whenever a signal arrives, and
2529 your main program checks this flag from time to time and then resets it.
2530 You can prevent additional @code{SIGALRM} signals from arriving in the
2531 meantime by wrapping the critical part of the code with calls to
2532 @code{sigprocmask}, like this:
2535 /* @r{This variable is set by the SIGALRM signal handler.} */
2536 volatile sig_atomic_t flag = 0;
2541 sigset_t block_alarm;
2545 /* @r{Initialize the signal mask.} */
2546 sigemptyset (&block_alarm);
2547 sigaddset (&block_alarm, SIGALRM);
2552 /* @r{Check if a signal has arrived; if so, reset the flag.} */
2553 sigprocmask (SIG_BLOCK, &block_alarm, NULL);
2556 @var{actions-if-not-arrived}
2559 sigprocmask (SIG_UNBLOCK, &block_alarm, NULL);
2567 @node Blocking for Handler
2568 @subsection Blocking Signals for a Handler
2569 @cindex blocking signals, in a handler
2571 When a signal handler is invoked, you usually want it to be able to
2572 finish without being interrupted by another signal. From the moment the
2573 handler starts until the moment it finishes, you must block signals that
2574 might confuse it or corrupt its data.
2576 When a handler function is invoked on a signal, that signal is
2577 automatically blocked (in addition to any other signals that are already
2578 in the process's signal mask) during the time the handler is running.
2579 If you set up a handler for @code{SIGTSTP}, for instance, then the
2580 arrival of that signal forces further @code{SIGTSTP} signals to wait
2581 during the execution of the handler.
2583 However, by default, other kinds of signals are not blocked; they can
2584 arrive during handler execution.
2586 The reliable way to block other kinds of signals during the execution of
2587 the handler is to use the @code{sa_mask} member of the @code{sigaction}
2599 install_handler (void)
2601 struct sigaction setup_action;
2602 sigset_t block_mask;
2604 sigemptyset (&block_mask);
2605 /* @r{Block other terminal-generated signals while handler runs.} */
2606 sigaddset (&block_mask, SIGINT);
2607 sigaddset (&block_mask, SIGQUIT);
2608 setup_action.sa_handler = catch_stop;
2609 setup_action.sa_mask = block_mask;
2610 setup_action.sa_flags = 0;
2611 sigaction (SIGTSTP, &setup_action, NULL);
2615 This is more reliable than blocking the other signals explicitly in the
2616 code for the handler. If you block signals explicity in the handler,
2617 you can't avoid at least a short interval at the beginning of the
2618 handler where they are not yet blocked.
2620 You cannot remove signals from the process's current mask using this
2621 mechanism. However, you can make calls to @code{sigprocmask} within
2622 your handler to block or unblock signals as you wish.
2624 In any case, when the handler returns, the system restores the mask that
2625 was in place before the handler was entered.
2627 @node Checking for Pending Signals
2628 @subsection Checking for Pending Signals
2629 @cindex pending signals, checking for
2630 @cindex blocked signals, checking for
2631 @cindex checking for pending signals
2633 You can find out which signals are pending at any time by calling
2634 @code{sigpending}. This function is declared in @file{signal.h}.
2639 @deftypefun int sigpending (sigset_t *@var{set})
2640 The @code{sigpending} function stores information about pending signals
2641 in @var{set}. If there is a pending signal that is blocked from
2642 delivery, then that signal is a member of the returned set. (You can
2643 test whether a particular signal is a member of this set using
2644 @code{sigismember}; see @ref{Signal Sets}.)
2646 The return value is @code{0} if successful, and @code{-1} on failure.
2649 Testing whether a signal is pending is not often useful. Testing when
2650 that signal is not blocked is almost certainly bad design.
2658 sigset_t base_mask, waiting_mask;
2660 sigemptyset (&base_mask);
2661 sigaddset (&base_mask, SIGINT);
2662 sigaddset (&base_mask, SIGTSTP);
2664 /* @r{Block user interrupts while doing other processing.} */
2665 sigprocmask (SIG_SETMASK, &base_mask, NULL);
2668 /* @r{After a while, check to see whether any signals are pending.} */
2669 sigpending (&waiting_mask);
2670 if (sigismember (&waiting_mask, SIGINT)) @{
2671 /* @r{User has tried to kill the process.} */
2673 else if (sigismember (&waiting_mask, SIGTSTP)) @{
2674 /* @r{User has tried to stop the process.} */
2678 Remember that if there is a particular signal pending for your process,
2679 additional signals of that same type that arrive in the meantime might
2680 be discarded. For example, if a @code{SIGINT} signal is pending when
2681 another @code{SIGINT} signal arrives, your program will probably only
2682 see one of them when you unblock this signal.
2684 @strong{Portability Note:} The @code{sigpending} function is new in
2685 POSIX.1. Older systems have no equivalent facility.
2687 @node Remembering a Signal
2688 @subsection Remembering a Signal to Act On Later
2690 Instead of blocking a signal using the library facilities, you can get
2691 almost the same results by making the handler set a flag to be tested
2692 later, when you ``unblock''. Here is an example:
2695 /* @r{If this flag is nonzero, don't handle the signal right away.} */
2696 volatile sig_atomic_t signal_pending;
2698 /* @r{This is nonzero if a signal arrived and was not handled.} */
2699 volatile sig_atomic_t defer_signal;
2702 handler (int signum)
2705 signal_pending = signum;
2707 @dots{} /* @r{``Really'' handle the signal.} */
2713 update_mumble (int frob)
2715 /* @r{Prevent signals from having immediate effect.} */
2717 /* @r{Now update @code{mumble}, without worrying about interruption.} */
2721 /* @r{We have updated @code{mumble}. Handle any signal that came in.} */
2723 if (defer_signal == 0 && signal_pending != 0)
2724 raise (signal_pending);
2728 Note how the particular signal that arrives is stored in
2729 @code{signal_pending}. That way, we can handle several types of
2730 inconvenient signals with the same mechanism.
2732 We increment and decrement @code{defer_signal} so that nested critical
2733 sections will work properly; thus, if @code{update_mumble} were called
2734 with @code{signal_pending} already nonzero, signals would be deferred
2735 not only within @code{update_mumble}, but also within the caller. This
2736 is also why we do not check @code{signal_pending} if @code{defer_signal}
2739 The incrementing and decrementing of @code{defer_signal} require more
2740 than one instruction; it is possible for a signal to happen in the
2741 middle. But that does not cause any problem. If the signal happens
2742 early enough to see the value from before the increment or decrement,
2743 that is equivalent to a signal which came before the beginning of the
2744 increment or decrement, which is a case that works properly.
2746 It is absolutely vital to decrement @code{defer_signal} before testing
2747 @code{signal_pending}, because this avoids a subtle bug. If we did
2748 these things in the other order, like this,
2751 if (defer_signal == 1 && signal_pending != 0)
2752 raise (signal_pending);
2757 then a signal arriving in between the @code{if} statement and the decrement
2758 would be effetively ``lost'' for an indefinite amount of time. The
2759 handler would merely set @code{defer_signal}, but the program having
2760 already tested this variable, it would not test the variable again.
2762 @cindex timing error in signal handling
2763 Bugs like these are called @dfn{timing errors}. They are especially bad
2764 because they happen only rarely and are nearly impossible to reproduce.
2765 You can't expect to find them with a debugger as you would find a
2766 reproducible bug. So it is worth being especially careful to avoid
2769 (You would not be tempted to write the code in this order, given the use
2770 of @code{defer_signal} as a counter which must be tested along with
2771 @code{signal_pending}. After all, testing for zero is cleaner than
2772 testing for one. But if you did not use @code{defer_signal} as a
2773 counter, and gave it values of zero and one only, then either order
2774 might seem equally simple. This is a further advantage of using a
2775 counter for @code{defer_signal}: it will reduce the chance you will
2776 write the code in the wrong order and create a subtle bug.)
2778 @node Waiting for a Signal
2779 @section Waiting for a Signal
2780 @cindex waiting for a signal
2781 @cindex @code{pause} function
2783 If your program is driven by external events, or uses signals for
2784 synchronization, then when it has nothing to do it should probably wait
2785 until a signal arrives.
2788 * Using Pause:: The simple way, using @code{pause}.
2789 * Pause Problems:: Why the simple way is often not very good.
2790 * Sigsuspend:: Reliably waiting for a specific signal.
2794 @subsection Using @code{pause}
2796 The simple way to wait until a signal arrives is to call @code{pause}.
2797 Please read about its disadvantages, in the following section, before
2802 @deftypefun int pause ()
2803 The @code{pause} function suspends program execution until a signal
2804 arrives whose action is either to execute a handler function, or to
2805 terminate the process.
2807 If the signal causes a handler function to be executed, then
2808 @code{pause} returns. This is considered an unsuccessful return (since
2809 ``successful'' behavior would be to suspend the program forever), so the
2810 return value is @code{-1}. Even if you specify that other primitives
2811 should resume when a system handler returns (@pxref{Interrupted
2812 Primitives}), this has no effect on @code{pause}; it always fails when a
2815 The following @code{errno} error conditions are defined for this function:
2819 The function was interrupted by delivery of a signal.
2822 If the signal causes program termination, @code{pause} doesn't return
2825 The @code{pause} function is declared in @file{unistd.h}.
2828 @node Pause Problems
2829 @subsection Problems with @code{pause}
2831 The simplicity of @code{pause} can conceal serious timing errors that
2832 can make a program hang mysteriously.
2834 It is safe to use @code{pause} if the real work of your program is done
2835 by the signal handlers themselves, and the ``main program'' does nothing
2836 but call @code{pause}. Each time a signal is delivered, the handler
2837 will do the next batch of work that is to be done, and then return, so
2838 that the main loop of the program can call @code{pause} again.
2840 You can't safely use @code{pause} to wait until one more signal arrives,
2841 and then resume real work. Even if you arrange for the signal handler
2842 to cooperate by setting a flag, you still can't use @code{pause}
2843 reliably. Here is an example of this problem:
2846 /* @r{@code{usr_interrupt} is set by the signal handler.} */
2850 /* @r{Do work once the signal arrives.} */
2855 This has a bug: the signal could arrive after the variable
2856 @code{usr_interrupt} is checked, but before the call to @code{pause}.
2857 If no further signals arrive, the process would never wake up again.
2859 You can put an upper limit on the excess waiting by using @code{sleep}
2860 in a loop, instead of using @code{pause}. (@xref{Sleeping}, for more
2861 about @code{sleep}.) Here is what this looks like:
2864 /* @r{@code{usr_interrupt} is set by the signal handler.}
2865 while (!usr_interrupt)
2868 /* @r{Do work once the signal arrives.} */
2872 For some purposes, that is good enough. But with a little more
2873 complexity, you can wait reliably until a particular signal handler is
2874 run, using @code{sigsuspend}.
2880 @subsection Using @code{sigsuspend}
2882 The clean and reliable way to wait for a signal to arrive is to block it
2883 and then use @code{sigsuspend}. By using @code{sigsuspend} in a loop,
2884 you can wait for certain kinds of signals, while letting other kinds of
2885 signals be handled by their handlers.
2889 @deftypefun int sigsuspend (const sigset_t *@var{set})
2890 This function replaces the process's signal mask with @var{set} and then
2891 suspends the process until a signal is delivered whose action is either
2892 to terminate the process or invoke a signal handling function. In other
2893 words, the program is effectively suspended until one of the signals that
2894 is not a member of @var{set} arrives.
2896 If the process is woken up by deliver of a signal that invokes a handler
2897 function, and the handler function returns, then @code{sigsuspend} also
2900 The mask remains @var{set} only as long as @code{sigsuspend} is waiting.
2901 The function @code{sigsuspend} always restores the previous signal mask
2904 The return value and error conditions are the same as for @code{pause}.
2907 With @code{sigsuspend}, you can replace the @code{pause} or @code{sleep}
2908 loop in the previous section with something completely reliable:
2911 sigset_t mask, oldmask;
2915 /* @r{Set up the mask of signals to temporarily block.} */
2916 sigemptyset (&mask);
2917 sigaddset (&mask, SIGUSR1);
2921 /* @r{Wait for a signal to arrive.} */
2922 sigprocmask (SIG_BLOCK, &mask, &oldmask);
2923 while (!usr_interrupt)
2924 sigsuspend (&oldmask);
2925 sigprocmask (SIG_UNBLOCK, &mask, NULL);
2928 This last piece of code is a little tricky. The key point to remember
2929 here is that when @code{sigsuspend} returns, it resets the process's
2930 signal mask to the original value, the value from before the call to
2931 @code{sigsuspend}---in this case, the @code{SIGUSR1} signal is once
2932 again blocked. The second call to @code{sigprocmask} is
2933 necessary to explicitly unblock this signal.
2935 One other point: you may be wondering why the @code{while} loop is
2936 necessary at all, since the program is apparently only waiting for one
2937 @code{SIGUSR1} signal. The answer is that the mask passed to
2938 @code{sigsuspend} permits the process to be woken up by the delivery of
2939 other kinds of signals, as well---for example, job control signals. If
2940 the process is woken up by a signal that doesn't set
2941 @code{usr_interrupt}, it just suspends itself again until the ``right''
2942 kind of signal eventually arrives.
2944 This technique takes a few more lines of preparation, but that is needed
2945 just once for each kind of wait criterion you want to use. The code
2946 that actually waits is just four lines.
2948 @node BSD Signal Handling
2949 @section BSD Signal Handling
2951 This section describes alternative signal handling functions derived
2952 from BSD Unix. These facilities were an advance, in their time; today,
2953 they are mostly obsolete, and supported mainly for compatibility with
2956 They do provide one feature that is not available through the POSIX
2957 functions: You can specify a separate stack for use in certain signal
2958 handlers. Using a signal stack is the only way you can handle a signal
2959 caused by stack overflow.
2962 * POSIX vs BSD:: Overview comparing BSD and POSIX signal
2967 @subsection POSIX and BSD Signal Facilities
2969 There are many similarities between the BSD and POSIX signal handling
2970 facilities, because the POSIX facilities were inspired by the BSD
2971 facilities. Besides having different names for all the functions to
2972 avoid conflicts, the main differences between the two are:
2976 BSD Unix represents signal masks as an @code{int} bit mask, rather than
2977 as a @code{sigset_t} object.
2980 The BSD facilities use a different default for whether an interrupted
2981 primitive should fail or resume. The POSIX facilities make system
2982 calls fail unless you specify that they should resume. With the BSD
2983 facility, the default is to make system calls resume unless you say they
2984 should fail. @xref{Interrupted Primitives}.
2987 BSD Unix has a concept of a @dfn{signal stack}. This is an alternate
2988 stack that is used during the execution of signal handler functions,
2989 instead of its normal execution stack.
2990 @cindex signal stack
2993 The BSD facilities are declared in @file{signal.h}.
2997 @section BSD Function to Establish a Handler
3001 @deftp {Data Type} {struct sigvec}
3002 This data type is the BSD equivalent of @code{struct sigaction}
3003 (@pxref{Advanced Signal Handling}); it is used to specify signal actions
3004 to the @code{sigvec} function. It contains the following members:
3007 @item sighandler_t sv_handler
3008 This is the handler function.
3011 This is the mask of additional signals to be blocked while the handler
3012 function is being called.
3015 This is a bit mask used to specify various flags which affect the
3016 behavior of the signal. You can also refer to this field as
3021 These symbolic constants can be used to provide values for the
3022 @code{sv_flags} field of a @code{sigvec} structure. This field is a bit
3023 mask value, so you bitwise-OR the flags of interest to you together.
3027 @deftypevr Macro int SV_ONSTACK
3028 If this bit is set in the @code{sv_flags} field of a @code{sigvec}
3029 structure, it means to use the signal stack when delivering the signal.
3034 @deftypevr Macro int SV_INTERRUPT
3035 If this bit is set in the @code{sv_flags} field of a @code{sigvec}
3036 structure, it means that system calls interrupted by this kind of signal
3037 should not be restarted if the handler returns; instead, the system
3038 calls should return with a @code{EINTR} error status. @xref{Interrupted
3044 @deftypevr Macro int SV_RESETHAND
3045 If this bit is set in the @code{sv_flags} field of a @code{sigvec}
3046 structure, it means to reset the action for the signal back to
3047 @code{SIG_DFL} when the signal is received.
3052 @deftypefun int sigvec (int @var{signum}, const struct sigvec *@var{action},struct sigvec *@var{old_action})
3053 This function is the equivalent of @code{sigaction} (@pxref{Advanced Signal
3054 Handling}); it installs the action @var{action} for the signal @var{signum},
3055 returning information about the previous action in effect for that signal
3056 in @var{old_action}.
3061 @deftypefun int siginterrupt (int @var{signum}, int @var{failflag})
3062 This function specifies which approach to use when certain primitives
3063 are interrupted by handling signal @var{signum}. If @var{failflag} is
3064 false, signal @var{signum} restarts primitives. If @var{failflag} is
3065 true, handling @var{signum} causes these primitives to fail with error
3066 code @code{EINTR}. @xref{Interrupted Primitives}.
3070 * Blocking in BSD:: BSD Functions for Blocking Signals.
3071 * Signal Stack:: Using a Separate Signal Stack.
3074 @node Blocking in BSD
3075 @subsection BSD Functions for Blocking Signals
3079 @deftypefn Macro int sigmask (int @var{signum})
3080 This macro returns a signal mask that has the bit for signal @var{signum}
3081 set. You can bitwise-OR the results of several calls to @code{sigmask}
3082 together to specify more than one signal. For example,
3085 (sigmask (SIGTSTP) | sigmask (SIGSTOP)
3086 | sigmask (SIGTTIN) | sigmask (SIGTTOU))
3090 specifies a mask that includes all the job-control stop signals.
3095 @deftypefun int sigblock (int @var{mask})
3096 This function is the equivalent of @code{sigprocmask} (@pxref{Process
3097 Signal Mask}) with a @var{how} argument of @code{SIG_BLOCK}: it adds the
3098 signals specified by @var{mask} to the calling process's signal mask.
3099 The return value is the previous set of blocked signals.
3104 @deftypefun int sigsetmask (int @var{mask})
3105 This function is the equivalent of @code{sigprocmask} (@pxref{Process
3106 Signal Mask}) with a @var{how} argument of @code{SIG_SETMASK}: it sets
3107 the calling process's signal mask to @var{mask}. The return value is
3108 the previous set of blocked signals.
3113 @deftypefun int sigpause (int @var{mask})
3114 This function is the equivalent of @code{sigsuspend} (@pxref{Waiting
3115 for a Signal}): it sets the calling process's signal mask to @var{mask},
3116 and waits for a signal to arrive. On return the previous set of blocked
3117 signals is restored.
3121 @subsection Using a Separate Signal Stack
3123 @c ??? Can we do better than recommending a magic constant size?
3124 A signal stack is a special area of memory to be used as the execution
3125 stack during signal handlers. It should be fairly large, to avoid any
3126 danger that it will overflow in turn---we recommend at least 16,000
3127 bytes. You can use @code{malloc} to allocate the space for the stack.
3128 Then call @code{sigstack} to tell the system to use that space for the
3131 You don't need to write signal handlers differently in order to use a
3132 signal stack. Switching from one stack to the other happens
3133 automatically. However, some debuggers on some machines may get
3134 confused if you examine a stack trace while a handler that uses the
3135 signal stack is running.
3139 @deftp {Data Type} {struct sigstack}
3140 This structure describes a signal stack. It contains the following members:
3144 This is the stack pointer.
3146 @item int ss_onstack
3147 This field is true if the process is currently using this stack.
3153 @deftypefun int sigstack (const struct sigstack *@var{stack}, struct sigstack *@var{oldstack})
3154 The @code{sigstack} function specifies an alternate stack for use during
3155 signal handling. When a signal is received by the process and its
3156 action indicates that the signal stack is used, the system arranges a
3157 switch to the currently installed signal stack while the handler for
3158 that signal is executed.
3160 If @var{oldstack} is not a null pointer, information about the currently
3161 installed signal stack is returned in the location it points to. If
3162 @var{stack} is not a null pointer, then this is installed as the new
3163 stack for use by signal handlers.
3165 The return value is @code{0} on success and @code{1} on failure.
3168 @c !!! 4.4 and GNU has a better interface: sigaltstack