* sysdeps/mach/hurd/dl-sysdep.c (_dl_sysdep_start): If started by
[glibc.git] / manual / signal.texi
blobbca02c528bd9caa054e526620df1fea6d614e501
1 @node Signal Handling, Process Startup, Non-Local Exits, Top
2 @chapter Signal Handling
4 @cindex signal
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
23 and synchronize.
25 @menu
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
37                                  arrives. 
38 * Signal Stack::                Using a Separate Signal Stack.
39 * BSD Signal Handling::         Additional functions for backward
40                                  compatibility with BSD.
41 @end menu
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
48 signals.
50 @menu
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
54                                  process. 
55 @end menu
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
62 signal:
64 @itemize @bullet
65 @item
66 A program error such as dividing by zero or issuing an address outside
67 the valid range.
69 @item
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.
75 @item
76 The termination of a child process.
78 @item
79 Expiration of a timer or alarm.
81 @item
82 A call to @code{kill} or @code{raise} by the same process.
84 @item
85 A call to @code{kill} from another process.  Signals are a limited but
86 useful form of interprocess communication.
88 @item
89 An attempt to perform an I/O operation that cannot be done.  Examples
90 are reading from a pipe that has no writer (@pxref{Pipes and FIFOs}),
91 and reading or writing to a terminal in certain situations (@pxref{Job
92 Control}).
93 @end itemize
95 Each of these kinds of events (excepting explicit calls to @code{kill}
96 and @code{raise}) generates its own particular kind of signal.  The
97 various kinds of signals are listed and described in detail in
98 @ref{Standard Signals}.
100 @node Signal Generation
101 @subsection Concepts of Signal Generation
102 @cindex generation of signals
104 In general, the events that generate signals fall into three major
105 categories: errors, external events, and explicit requests.
107 An error means that a program has done something invalid and cannot
108 continue execution.  But not all kinds of errors generate signals---in
109 fact, most do not.  For example, opening a nonexistent file is an error,
110 but it does not raise a signal; instead, @code{open} returns @code{-1}.
111 In general, errors that are necessarily associated with certain library
112 functions are reported by returning a value that indicates an error.
113 The errors which raise signals are those which can happen anywhere in
114 the program, not just in library calls.  These include division by zero
115 and invalid memory addresses.
117 An external event generally has to do with I/O or other processes.
118 These include the arrival of input, the expiration of a timer, and the
119 termination of a child process.
121 An explicit request means the use of a library function such as
122 @code{kill} whose purpose is specifically to generate a signal.
124 Signals may be generated @dfn{synchronously} or @dfn{asynchronously}.  A
125 synchronous signal pertains to a specific action in the program, and is
126 delivered (unless blocked) during that action.  Most errors generate
127 signals synchronously, and so do explicit requests by a process to
128 generate a signal for that same process.  On some machines, certain
129 kinds of hardware errors (usually floating-point exceptions) are not
130 reported completely synchronously, but may arrive a few instructions
131 later.
133 Asynchronous signals are generated by events outside the control of the
134 process that receives them.  These signals arrive at unpredictable times
135 during execution.  External events generate signals asynchronously, and
136 so do explicit requests that apply to some other process.
138 A given type of signal is either typically synchrous or typically
139 asynchronous.  For example, signals for errors are typically synchronous
140 because errors generate signals synchronously.  But any type of signal
141 can be generated synchronously or asynchronously with an explicit
142 request.
144 @node Delivery of Signal
145 @subsection How Signals Are Delivered
146 @cindex delivery of signals
147 @cindex pending signals
148 @cindex blocked signals
150 When a signal is generated, it becomes @dfn{pending}.  Normally it
151 remains pending for just a short period of time and then is
152 @dfn{delivered} to the process that was signaled.  However, if that kind
153 of signal is currently @dfn{blocked}, it may remain pending
154 indefinitely---until signals of that kind are @dfn{unblocked}.  Once
155 unblocked, it will be delivered immediately.  @xref{Blocking Signals}.
157 @cindex specified action (for a signal)
158 @cindex default action (for a signal)
159 @cindex signal action
160 @cindex catching signals
161 When the signal is delivered, whether right away or after a long delay,
162 the @dfn{specified action} for that signal is taken.  For certain
163 signals, such as @code{SIGKILL} and @code{SIGSTOP}, the action is fixed,
164 but for most signals, the program has a choice: ignore the signal,
165 specify a @dfn{handler function}, or accept the @dfn{default action} for
166 that kind of signal.  The program specifies its choice using functions
167 such as @code{signal} or @code{sigaction} (@pxref{Signal Actions}).  We
168 sometimes say that a handler @dfn{catches} the signal.  While the
169 handler is running, that particular signal is normally blocked.
171 If the specified action for a kind of signal is to ignore it, then any
172 such signal which is generated is discarded immediately.  This happens
173 even if the signal is also blocked at the time.  A signal discarded in
174 this way will never be delivered, not even if the program subsequently
175 specifies a different action for that kind of signal and then unblocks
178 If a signal arrives which the program has neither handled nor ignored,
179 its @dfn{default action} takes place.  Each kind of signal has its own
180 default action, documented below (@pxref{Standard Signals}).  For most kinds
181 of signals, the default action is to terminate the process.  For certain
182 kinds of signals that represent ``harmless'' events, the default action
183 is to do nothing.
185 When a signal terminates a process, its parent process can determine the
186 cause of termination by examining the termination status code reported
187 by the @code{wait} or @code{waitpid} functions.  (This is discussed in
188 more detail in @ref{Process Completion}.)  The information it can get
189 includes the fact that termination was due to a signal, and the kind of
190 signal involved.  If a program you run from a shell is terminated by a
191 signal, the shell typically prints some kind of error message.
193 The signals that normally represent program errors have a special
194 property: when one of these signals terminates the process, it also
195 writes a @dfn{core dump file} which records the state of the process at
196 the time of termination.  You can examine the core dump with a debugger
197 to investigate what caused the error.
199 If you raise a ``program error'' signal by explicit request, and this
200 terminates the process, it makes a core dump file just as if the signal
201 had been due directly to an error.
203 @node Standard Signals
204 @section Standard Signals
205 @cindex signal names
206 @cindex names of signals
208 @pindex signal.h
209 @cindex signal number
210 This section lists the names for various standard kinds of signals and
211 describes what kind of event they mean.  Each signal name is a macro
212 which stands for a positive integer---the @dfn{signal number} for that
213 kind of signal.  Your programs should never make assumptions about the
214 numeric code for a particular kind of signal, but rather refer to them
215 always by the names defined here.  This is because the number for a
216 given kind of signal can vary from system to system, but the meanings of
217 the names are standardized and fairly uniform.
219 The signal names are defined in the header file @file{signal.h}.
221 @comment signal.h
222 @comment BSD
223 @deftypevr Macro int NSIG
224 The value of this symbolic constant is the total number of signals
225 defined.  Since the signal numbers are allocated consecutively,
226 @code{NSIG} is also one greater than the largest defined signal number.
227 @end deftypevr
229 @menu
230 * Program Error Signals::       Used to report serious program errors.
231 * Termination Signals::         Used to interrupt and/or terminate the
232                                  program. 
233 * Alarm Signals::               Used to indicate expiration of timers.
234 * Asynchronous I/O Signals::    Used to indicate input is available.
235 * Job Control Signals::         Signals used to support job control.
236 * Operation Error Signals::     Used to report operational system errors.
237 * Miscellaneous Signals::       Miscellaneous Signals.
238 * Signal Messages::             Printing a message describing a signal.
239 @end menu
241 @node Program Error Signals
242 @subsection Program Error Signals
243 @cindex program error signals
245 The following signals are generated when a serious program error is
246 detected by the operating system or the computer itself.  In general,
247 all of these signals are indications that your program is seriously
248 broken in some way, and there's usually no way to continue the
249 computation which encountered the error.
251 Some programs handle program error signals in order to tidy up before
252 terminating; for example, programs that turn off echoing of terminal
253 input should handle program error signals in order to turn echoing back
254 on.  The handler should end by specifying the default action for the
255 signal that happened and then reraising it; this will cause the program
256 to terminate with that signal, as if it had not had a handler.
257 (@xref{Termination in Handler}.)
259 Termination is the sensible ultimate outcome from a program error in
260 most programs.  However, programming systems such as Lisp that can load
261 compiled user programs might need to keep executing even if a user
262 program incurs an error.  These programs have handlers which use
263 @code{longjmp} to return control to the command level.
265 The default action for all of these signals is to cause the process to
266 terminate.  If you block or ignore these signals or establish handlers
267 for them that return normally, your program will probably break horribly
268 when such signals happen, unless they are generated by @code{raise} or
269 @code{kill} instead of a real error.
271 @vindex COREFILE
272 When one of these program error signals terminates a process, it also
273 writes a @dfn{core dump file} which records the state of the process at
274 the time of termination.  The core dump file is named @file{core} and is
275 written in whichever directory is current in the process at the time.
276 (On the GNU system, you can specify the file name for core dumps with
277 the environment variable @code{COREFILE}.)  The purpose of core dump
278 files is so that you can examine them with a debugger to investigate
279 what caused the error.
281 @comment signal.h
282 @comment ANSI
283 @deftypevr Macro int SIGFPE
284 The @code{SIGFPE} signal reports a fatal arithmetic error.  Although the
285 name is derived from ``floating-point exception'', this signal actually
286 covers all arithmetic errors, including division by zero and overflow.
287 If a program stores integer data in a location which is then used in a
288 floating-point operation, this often causes an ``invalid operation''
289 exception, because the processor cannot recognize the data as a
290 floating-point number.
291 @cindex exception
292 @cindex floating-point exception
294 Actual floating-point exceptions are a complicated subject because there
295 are many types of exceptions with subtly different meanings, and the
296 @code{SIGFPE} signal doesn't distinguish between them.  The @cite{IEEE
297 Standard for Binary Floating-Point Arithmetic (ANSI/IEEE Std 754-1985)}
298 defines various floating-point exceptions and requires conforming
299 computer systems to report their occurrences.  However, this standard
300 does not specify how the exceptions are reported, or what kinds of
301 handling and control the operating system can offer to the programmer.
302 @end deftypevr
304 BSD systems provide the @code{SIGFPE} handler with an extra argument
305 that distinguishes various causes of the exception.  In order to access
306 this argument, you must define the handler to accept two arguments,
307 which means you must cast it to a one-argument function type in order to
308 establish the handler.  The GNU library does provide this extra
309 argument, but the value is meaningful only on operating systems that
310 provide the information (BSD systems and GNU systems).
312 @table @code
313 @comment signal.h
314 @comment BSD
315 @item FPE_INTOVF_TRAP
316 @vindex FPE_INTOVF_TRAP
317 Integer overflow (impossible in a C program unless you enable overflow
318 trapping in a hardware-specific fashion).
319 @comment signal.h
320 @comment BSD
321 @item FPE_INTDIV_TRAP
322 @vindex FPE_INTDIV_TRAP
323 Integer division by zero.
324 @comment signal.h
325 @comment BSD
326 @item FPE_SUBRNG_TRAP
327 @vindex FPE_SUBRNG_TRAP
328 Subscript-range (something that C programs never check for).
329 @comment signal.h
330 @comment BSD
331 @item FPE_FLTOVF_TRAP
332 @vindex FPE_FLTOVF_TRAP
333 Floating overflow trap.
334 @comment signal.h
335 @comment BSD
336 @item FPE_FLTDIV_TRAP
337 @vindex FPE_FLTDIV_TRAP
338 Floating/decimal division by zero.
339 @comment signal.h
340 @comment BSD
341 @item FPE_FLTUND_TRAP
342 @vindex FPE_FLTUND_TRAP
343 Floating underflow trap.  (Trapping on floating underflow is not
344 normally enabled.)
345 @comment signal.h
346 @comment BSD
347 @item FPE_DECOVF_TRAP
348 @vindex FPE_DECOVF_TRAP
349 Decimal overflow trap.  (Only a few machines have decimal arithmetic and
350 C never uses it.)
351 @ignore @c These seem redundant
352 @comment signal.h
353 @comment BSD
354 @item FPE_FLTOVF_FAULT
355 @vindex FPE_FLTOVF_FAULT
356 Floating overflow fault.
357 @comment signal.h
358 @comment BSD
359 @item FPE_FLTDIV_FAULT
360 @vindex FPE_FLTDIV_FAULT
361 Floating divide by zero fault.
362 @comment signal.h
363 @comment BSD
364 @item FPE_FLTUND_FAULT
365 @vindex FPE_FLTUND_FAULT
366 Floating underflow fault.
367 @end ignore
368 @end table
370 @comment signal.h
371 @comment ANSI
372 @deftypevr Macro int SIGILL
373 The name of this signal is derived from ``illegal instruction''; it
374 usually means your program is trying to execute garbage or a privileged
375 instruction.  Since the C compiler generates only valid instructions,
376 @code{SIGILL} typically indicates that the executable file is corrupted,
377 or that you are trying to execute data.  Some common ways of getting
378 into the latter situation are by passing an invalid object where a
379 pointer to a function was expected, or by writing past the end of an
380 automatic array (or similar problems with pointers to automatic
381 variables) and corrupting other data on the stack such as the return
382 address of a stack frame.
384 @code{SIGILL} can also be generated when the stack overflows, or when
385 the system has trouble running the handler for a signal.
386 @end deftypevr
387 @cindex illegal instruction
389 @comment signal.h
390 @comment ANSI
391 @deftypevr Macro int SIGSEGV
392 @cindex segmentation violation
393 This signal is generated when a program tries to read or write outside
394 the memory that is allocated for it, or to write memory that can only be
395 read.  (Actually, the signals only occur when the program goes far
396 enough outside to be detected by the system's memory protection
397 mechanism.)  The name is an abbreviation for ``segmentation violation''.
399 Common ways of getting a @code{SIGSEGV} condition include dereferencing
400 a null or uninitialized pointer, or when you use a pointer to step
401 through an array, but fail to check for the end of the array.  It varies
402 among systems whether dereferencing a null pointer generates
403 @code{SIGSEGV} or @code{SIGBUS}.
404 @end deftypevr
406 @comment signal.h
407 @comment BSD
408 @deftypevr Macro int SIGBUS
409 This signal is generated when an invalid pointer is dereferenced.  Like
410 @code{SIGSEGV}, this signal is typically the result of dereferencing an
411 uninitialized pointer.  The difference between the two is that
412 @code{SIGSEGV} indicates an invalid access to valid memory, while
413 @code{SIGBUS} indicates an access to an invalid address.  In particular,
414 @code{SIGBUS} signals often result from dereferencing a misaligned
415 pointer, such as referring to a four-word integer at an address not
416 divisible by four.  (Each kind of computer has its own requirements for
417 address alignment.)
419 The name of this signal is an abbreviation for ``bus error''.
420 @end deftypevr
421 @cindex bus error
423 @comment signal.h
424 @comment ANSI
425 @deftypevr Macro int SIGABRT
426 @cindex abort signal
427 This signal indicates an error detected by the program itself and
428 reported by calling @code{abort}.  @xref{Aborting a Program}.
429 @end deftypevr
431 @comment signal.h
432 @comment Unix
433 @deftypevr Macro int SIGIOT
434 Generated by the PDP-11 ``iot'' instruction.  On most machines, this is
435 just another name for @code{SIGABRT}.
436 @end deftypevr
438 @comment signal.h
439 @comment BSD
440 @deftypevr Macro int SIGTRAP
441 Generated by the machine's breakpoint instruction, and possibly other
442 trap instructions.  This signal is used by debuggers.  Your program will
443 probably only see @code{SIGTRAP} if it is somehow executing bad
444 instructions.
445 @end deftypevr
447 @comment signal.h
448 @comment BSD
449 @deftypevr Macro int  SIGEMT
450 Emulator trap; this results from certain unimplemented instructions
451 which might be emulated in software, or the operating system's
452 failure to properly emulate them.
453 @end deftypevr
455 @comment signal.h
456 @comment Unix
457 @deftypevr Macro int  SIGSYS
458 Bad system call; that is to say, the instruction to trap to the
459 operating system was executed, but the code number for the system call
460 to perform was invalid.
461 @end deftypevr
463 @node Termination Signals
464 @subsection Termination Signals
465 @cindex program termination signals
467 These signals are all used to tell a process to terminate, in one way
468 or another.  They have different names because they're used for slightly
469 different purposes, and programs might want to handle them differently.
471 The reason for handling these signals is usually so your program can
472 tidy up as appropriate before actually terminating.  For example, you
473 might want to save state information, delete temporary files, or restore
474 the previous terminal modes.  Such a handler should end by specifying
475 the default action for the signal that happened and then reraising it;
476 this will cause the program to terminate with that signal, as if it had
477 not had a handler.  (@xref{Termination in Handler}.)
479 The (obvious) default action for all of these signals is to cause the
480 process to terminate.
482 @comment signal.h
483 @comment ANSI
484 @deftypevr Macro int SIGTERM
485 @cindex termination signal
486 The @code{SIGTERM} signal is a generic signal used to cause program
487 termination.  Unlike @code{SIGKILL}, this signal can be blocked,
488 handled, and ignored.  It is the normal way to politely ask a program to
489 terminate.
491 The shell command @code{kill} generates @code{SIGTERM} by default.
492 @pindex kill
493 @end deftypevr
495 @comment signal.h
496 @comment ANSI
497 @deftypevr Macro int SIGINT
498 @cindex interrupt signal
499 The @code{SIGINT} (``program interrupt'') signal is sent when the user
500 types the INTR character (normally @kbd{C-c}).  @xref{Special
501 Characters}, for information about terminal driver support for
502 @kbd{C-c}.
503 @end deftypevr
505 @comment signal.h
506 @comment POSIX.1
507 @deftypevr Macro int SIGQUIT
508 @cindex quit signal
509 @cindex quit signal
510 The @code{SIGQUIT} signal is similar to @code{SIGINT}, except that it's
511 controlled by a different key---the QUIT character, usually
512 @kbd{C-\}---and produces a core dump when it terminates the process,
513 just like a program error signal.  You can think of this as a
514 program error condition ``detected'' by the user.
516 @xref{Program Error Signals}, for information about core dumps.
517 @xref{Special Characters}, for information about terminal driver
518 support.
520 Certain kinds of cleanups are best omitted in handling @code{SIGQUIT}.
521 For example, if the program creates temporary files, it should handle
522 the other termination requests by deleting the temporary files.  But it
523 is better for @code{SIGQUIT} not to delete them, so that the user can
524 examine them in conjunction with the core dump.
525 @end deftypevr
527 @comment signal.h
528 @comment POSIX.1
529 @deftypevr Macro int SIGKILL
530 The @code{SIGKILL} signal is used to cause immediate program termination.
531 It cannot be handled or ignored, and is therefore always fatal.  It is
532 also not possible to block this signal.
534 This signal is usually generated only by explicit request.  Since it
535 cannot be handled, you should generate it only as a last resort, after
536 first trying a less drastic method such as @kbd{C-c} or @code{SIGTERM}.
537 If a process does not respond to any other termination signals, sending
538 it a @code{SIGKILL} signal will almost always cause it to go away.
540 In fact, if @code{SIGKILL} fails to terminate a process, that by itself
541 constitutes an operating system bug which you should report.
543 The system will generate @code{SIGKILL} for a process itself under some
544 unusual conditions where the program cannot possible continue to run
545 (even to run a signal handler).
546 @end deftypevr
547 @cindex kill signal
549 @comment signal.h
550 @comment POSIX.1
551 @deftypevr Macro int SIGHUP
552 @cindex hangup signal
553 The @code{SIGHUP} (``hang-up'') signal is used to report that the user's
554 terminal is disconnected, perhaps because a network or telephone
555 connection was broken.  For more information about this, see @ref{Control
556 Modes}.
558 This signal is also used to report the termination of the controlling
559 process on a terminal to jobs associated with that session; this
560 termination effectively disconnects all processes in the session from
561 the controlling terminal.  For more information, see @ref{Termination
562 Internals}.
563 @end deftypevr
565 @node Alarm Signals
566 @subsection Alarm Signals
568 These signals are used to indicate the expiration of timers.
569 @xref{Setting an Alarm}, for information about functions that cause
570 these signals to be sent.
572 The default behavior for these signals is to cause program termination.
573 This default is rarely useful, but no other default would be useful;
574 most of the ways of using these signals would require handler functions
575 in any case.
577 @comment signal.h
578 @comment POSIX.1
579 @deftypevr Macro int SIGALRM
580 This signal typically indicates expiration of a timer that measures real
581 or clock time.  It is used by the @code{alarm} function, for example.
582 @end deftypevr
583 @cindex alarm signal
585 @comment signal.h
586 @comment BSD
587 @deftypevr Macro int SIGVTALRM
588 This signal typically indicates expiration of a timer that measures CPU
589 time used by the current process.  The name is an abbreviation for
590 ``virtual time alarm''.
591 @end deftypevr
592 @cindex virtual time alarm signal
594 @comment signal.h
595 @comment BSD
596 @deftypevr Macro int SIGPROF
597 This signal is typically indicates expiration of a timer that measures
598 both CPU time used by the current process, and CPU time expended on 
599 behalf of the process by the system.  Such a timer is used to implement
600 code profiling facilities, hence the name of this signal.
601 @end deftypevr
602 @cindex profiling alarm signal
605 @node Asynchronous I/O Signals
606 @subsection Asynchronous I/O Signals
608 The signals listed in this section are used in conjunction with
609 asynchronous I/O facilities.  You have to take explicit action by
610 calling @code{fcntl} to enable a particular file descriptior to generate
611 these signals (@pxref{Interrupt Input}).  The default action for these
612 signals is to ignore them.
614 @comment signal.h
615 @comment BSD
616 @deftypevr Macro int SIGIO
617 @cindex input available signal
618 @cindex output possible signal
619 This signal is sent when a file descriptor is ready to perform input
620 or output.
622 On most operating systems, terminals and sockets are the only kinds of
623 files that can generate @code{SIGIO}; other kinds, including ordinary
624 files, never generate @code{SIGIO} even if you ask them to.
626 In the GNU system @code{SIGIO} will always be generated properly 
627 if you successfully set asynchronous mode with @code{fcntl}.
628 @end deftypevr
630 @comment signal.h
631 @comment BSD
632 @deftypevr Macro int SIGURG
633 @cindex urgent data signal
634 This signal is sent when ``urgent'' or out-of-band data arrives on a
635 socket.  @xref{Out-of-Band Data}.
636 @end deftypevr
638 @comment signal.h
639 @comment SVID
640 @deftypevr Macro int SIGPOLL
641 This is a System V signal name, more or less similar to @code{SIGIO}.
642 It is defined only for compatibility.
643 @end deftypevr
645 @node Job Control Signals
646 @subsection Job Control Signals
647 @cindex job control signals
649 These signals are used to support job control.  If your system
650 doesn't support job control, then these macros are defined but the
651 signals themselves can't be raised or handled.
653 You should generally leave these signals alone unless you really
654 understand how job control works.  @xref{Job Control}.
656 @comment signal.h
657 @comment POSIX.1
658 @deftypevr Macro int SIGCHLD
659 @cindex child process signal
660 This signal is sent to a parent process whenever one of its child
661 processes terminates or stops.
663 The default action for this signal is to ignore it.  If you establish a
664 handler for this signal while there are child processes that have
665 terminated but not reported their status via @code{wait} or
666 @code{waitpid} (@pxref{Process Completion}), whether your new handler
667 applies to those processes or not depends on the particular operating
668 system.
669 @end deftypevr
671 @comment signal.h
672 @comment SVID
673 @deftypevr Macro int SIGCLD
674 This is an obsolete name for @code{SIGCHLD}.
675 @end deftypevr
677 @comment signal.h
678 @comment POSIX.1
679 @deftypevr Macro int SIGCONT
680 @cindex continue signal
681 You can send a @code{SIGCONT} signal to a process to make it continue.
682 This signal is special---it always makes the process continue if it is
683 stopped, before the signal is delivered.  The default behavior is to do
684 nothing else.  You cannot block this signal.  You can set a handler, but
685 @code{SIGCONT} always makes the process continue regardless.
687 Most programs have no reason to handle @code{SIGCONT}; they simply
688 resume execution without realizing they were ever stopped.  You can use
689 a handler for @code{SIGCONT} to make a program do something special when
690 it is stopped and continued---for example, to reprint a prompt when it
691 is suspended while waiting for input.
692 @end deftypevr
694 @comment signal.h
695 @comment POSIX.1
696 @deftypevr Macro int SIGSTOP
697 The @code{SIGSTOP} signal stops the process.  It cannot be handled,
698 ignored, or blocked.
699 @end deftypevr
700 @cindex stop signal
702 @comment signal.h
703 @comment POSIX.1
704 @deftypevr Macro int SIGTSTP
705 The @code{SIGTSTP} signal is an interactive stop signal.  Unlike
706 @code{SIGSTOP}, this signal can be handled and ignored.  
708 Your program should handle this signal if you have a special need to
709 leave files or system tables in a secure state when a process is
710 stopped.  For example, programs that turn off echoing should handle
711 @code{SIGTSTP} so they can turn echoing back on before stopping.
713 This signal is generated when the user types the SUSP character
714 (normally @kbd{C-z}).  For more information about terminal driver
715 support, see @ref{Special Characters}.
716 @end deftypevr
717 @cindex interactive stop signal
719 @comment signal.h
720 @comment POSIX.1
721 @deftypevr Macro int SIGTTIN
722 A process cannot read from the the user's terminal while it is running 
723 as a background job.  When any process in a background job tries to
724 read from the terminal, all of the processes in the job are sent a
725 @code{SIGTTIN} signal.  The default action for this signal is to
726 stop the process.  For more information about how this interacts with
727 the terminal driver, see @ref{Access to the Terminal}.
728 @end deftypevr
729 @cindex terminal input signal
731 @comment signal.h
732 @comment POSIX.1
733 @deftypevr Macro int SIGTTOU
734 This is similar to @code{SIGTTIN}, but is generated when a process in a
735 background job attempts to write to the terminal or set its modes.
736 Again, the default action is to stop the process.  @code{SIGTTOU} is
737 only generated for an attempt to write to the terminal if the
738 @code{TOSTOP} output mode is set; @pxref{Output Modes}.
739 @end deftypevr
740 @cindex terminal output signal
742 While a process is stopped, no more signals can be delivered to it until
743 it is continued, except @code{SIGKILL} signals and (obviously)
744 @code{SIGCONT} signals.  The signals are marked as pending, but not
745 delivered until the process is continued.  The @code{SIGKILL} signal
746 always causes termination of the process and can't be blocked, handled
747 or ignored.  You can ignore @code{SIGCONT}, but it always causes the
748 process to be continued anyway if it is stopped.  Sending a
749 @code{SIGCONT} signal to a process causes any pending stop signals for
750 that process to be discarded.  Likewise, any pending @code{SIGCONT}
751 signals for a process are discarded when it receives a stop signal.
753 When a process in an orphaned process group (@pxref{Orphaned Process
754 Groups}) receives a @code{SIGTSTP}, @code{SIGTTIN}, or @code{SIGTTOU}
755 signal and does not handle it, the process does not stop.  Stopping the
756 process would probably not be very useful, since there is no shell
757 program that will notice it stop and allow the user to continue it.
758 What happens instead depends on the operating system you are using.
759 Some systems may do nothing; others may deliver another signal instead,
760 such as @code{SIGKILL} or @code{SIGHUP}.  In the GNU system, the process
761 dies with @code{SIGKILL}; this avoids the problem of many stopped,
762 orphaned processes lying around the system.
764 @ignore
765 On the GNU system, it is possible to reattach to the orphaned process
766 group and continue it, so stop signals do stop the process as usual on
767 a GNU system unless you have requested POSIX compatibility ``till it
768 hurts.''
769 @end ignore
771 @node Operation Error Signals
772 @subsection Operation Error Signals
774 These signals are used to report various errors generated by an
775 operation done by the program.  They do not necessarily indicate a
776 programming error in the program, but an error that prevents an
777 operating system call from completing.  The default action for all of
778 them is to cause the process to terminate.
780 @comment signal.h
781 @comment POSIX.1
782 @deftypevr Macro int SIGPIPE
783 @cindex pipe signal
784 @cindex broken pipe signal
785 Broken pipe.  If you use pipes or FIFOs, you have to design your
786 application so that one process opens the pipe for reading before
787 another starts writing.  If the reading process never starts, or
788 terminates unexpectedly, writing to the pipe or FIFO raises a
789 @code{SIGPIPE} signal.  If @code{SIGPIPE} is blocked, handled or
790 ignored, the offending call fails with @code{EPIPE} instead.
792 Pipes and FIFO special files are discussed in more detail in @ref{Pipes
793 and FIFOs}.
795 Another cause of @code{SIGPIPE} is when you try to output to a socket
796 that isn't connected.  @xref{Sending Data}.
797 @end deftypevr
799 @comment signal.h
800 @comment GNU
801 @deftypevr Macro int SIGLOST
802 @cindex lost resource signal
803 Resource lost.  This signal is generated when you have an advisory lock
804 on an NFS file, and the NFS server reboots and forgets about your lock.
806 In the GNU system, @code{SIGLOST} is generated when any server program
807 dies unexpectedly.  It is usually fine to ignore the signal; whatever
808 call was made to the server that died just returns an error.
809 @end deftypevr
811 @comment signal.h
812 @comment BSD
813 @deftypevr Macro int SIGXCPU
814 CPU time limit exceeded.  This signal is generated when the process
815 exceeds its soft resource limit on CPU time.  @xref{Limits on Resources}.
816 @end deftypevr
818 @comment signal.h
819 @comment BSD
820 @deftypevr Macro int SIGXFSZ
821 File size limit exceeded.  This signal is generated when the process
822 attempts to extend a file so it exceeds the process's soft resource
823 limit on file size.  @xref{Limits on Resources}.
824 @end deftypevr
826 @node Miscellaneous Signals
827 @subsection Miscellaneous Signals
829 These signals are used for various other purposes.  In general, they
830 will not affect your program unless it explicitly uses them for something.
832 @comment signal.h
833 @comment POSIX.1
834 @deftypevr Macro int SIGUSR1
835 @end deftypevr
836 @comment signal.h
837 @comment POSIX.1
838 @deftypevr Macro int SIGUSR2
839 @cindex user signals
840 The @code{SIGUSR1} and @code{SIGUSR2} signals are set aside for you to
841 use any way you want.  They're useful for simple interprocess
842 communication, if you write a signal handler for them in the program
843 that receives the signal.
845 There is an example showing the use of @code{SIGUSR1} and @code{SIGUSR2}
846 in @ref{Signaling Another Process}.
848 The default action is to terminate the process.
849 @end deftypevr
851 @comment signal.h
852 @comment BSD
853 @deftypevr Macro int SIGWINCH
854 Window size change.  This is generated on some systems (including GNU)
855 when the terminal driver's record of the number of rows and columns on
856 the screen is changed.  The default action is to ignore it.
858 If a program does full-screen display, it should handle @code{SIGWINCH}.
859 When the signal arrives, it should fetch the new screen size and
860 reformat its display accordingly.
861 @end deftypevr
863 @comment signal.h
864 @comment BSD
865 @deftypevr Macro int SIGINFO
866 Information request.  In 4.4 BSD and the GNU system, this signal is sent
867 to all the processes in the foreground process group of the controlling
868 terminal when the user types the STATUS character in canonical mode;
869 @pxref{Signal Characters}.
871 If the process is the leader of the process group, the default action is
872 to print some status information about the system and what the process
873 is doing.  Otherwise the default is to do nothing.
874 @end deftypevr
876 @node Signal Messages
877 @subsection Signal Messages
878 @cindex signal messages
880 We mentioned above that the shell prints a message describing the signal
881 that terminated a child process.  The clean way to print a message
882 describing a signal is to use the functions @code{strsignal} and
883 @code{psignal}.  These functions use a signal number to specify which
884 kind of signal to describe.  The signal number may come from the
885 termination status of a child process (@pxref{Process Completion}) or it
886 may come from a signal handler in the same process.
888 @comment string.h
889 @comment GNU
890 @deftypefun {char *} strsignal (int @var{signum})
891 This function returns a pointer to a statically-allocated string
892 containing a message describing the signal @var{signum}.  You
893 should not modify the contents of this string; and, since it can be
894 rewritten on subsequent calls, you should save a copy of it if you need
895 to reference it later.
897 @pindex string.h
898 This function is a GNU extension, declared in the header file
899 @file{string.h}.
900 @end deftypefun
902 @comment signal.h
903 @comment BSD
904 @deftypefun void psignal (int @var{signum}, const char *@var{message})
905 This function prints a message describing the signal @var{signum} to the
906 standard error output stream @code{stderr}; see @ref{Standard Streams}.
908 If you call @code{psignal} with a @var{message} that is either a null
909 pointer or an empty string, @code{psignal} just prints the message 
910 corresponding to @var{signum}, adding a trailing newline.
912 If you supply a non-null @var{message} argument, then @code{psignal}
913 prefixes its output with this string.  It adds a colon and a space 
914 character to separate the @var{message} from the string corresponding
915 to @var{signum}.
917 @pindex stdio.h
918 This function is a BSD feature, declared in the header file @file{signal.h}.
919 @end deftypefun
921 @vindex sys_siglist
922 There is also an array @code{sys_siglist} which contains the messages
923 for the various signal codes.  This array exists on BSD systems, unlike
924 @code{strsignal}.
926 @node Signal Actions
927 @section Specifying Signal Actions
928 @cindex signal actions
929 @cindex establishing a handler
931 The simplest way to change the action for a signal is to use the
932 @code{signal} function.  You can specify a built-in action (such as to
933 ignore the signal), or you can @dfn{establish a handler}.
935 The GNU library also implements the more versatile @code{sigaction}
936 facility.  This section describes both facilities and gives suggestions
937 on which to use when.
939 @menu
940 * Basic Signal Handling::       The simple @code{signal} function.
941 * Advanced Signal Handling::    The more powerful @code{sigaction} function.
942 * Signal and Sigaction::        How those two functions interact.
943 * Sigaction Function Example::  An example of using the sigaction function.
944 * Flags for Sigaction::         Specifying options for signal handling.
945 * Initial Signal Actions::      How programs inherit signal actions.
946 @end menu
948 @node Basic Signal Handling
949 @subsection Basic Signal Handling
950 @cindex @code{signal} function
952 The @code{signal} function provides a simple interface for establishing
953 an action for a particular signal.  The function and associated macros
954 are declared in the header file @file{signal.h}.
955 @pindex signal.h
957 @comment signal.h
958 @comment GNU
959 @deftp {Data Type} sighandler_t
960 This is the type of signal handler functions.  Signal handlers take one
961 integer argument specifying the signal number, and have return type
962 @code{void}.  So, you should define handler functions like this:
964 @smallexample
965 void @var{handler} (int @code{signum}) @{ @dots{} @}
966 @end smallexample
968 The name @code{sighandler_t} for this data type is a GNU extension.
969 @end deftp
971 @comment signal.h
972 @comment ANSI
973 @deftypefun sighandler_t signal (int @var{signum}, sighandler_t @var{action})
974 The @code{signal} function establishes @var{action} as the action for
975 the signal @var{signum}.
977 The first argument, @var{signum}, identifies the signal whose behavior
978 you want to control, and should be a signal number.  The proper way to
979 specify a signal number is with one of the symbolic signal names
980 described in @ref{Standard Signals}---don't use an explicit number, because
981 the numerical code for a given kind of signal may vary from operating
982 system to operating system.
984 The second argument, @var{action}, specifies the action to use for the
985 signal @var{signum}.  This can be one of the following:
987 @table @code
988 @item SIG_DFL
989 @vindex SIG_DFL
990 @cindex default action for a signal
991 @code{SIG_DFL} specifies the default action for the particular signal.
992 The default actions for various kinds of signals are stated in
993 @ref{Standard Signals}.
995 @item SIG_IGN
996 @vindex SIG_IGN
997 @cindex ignore action for a signal
998 @code{SIG_IGN} specifies that the signal should be ignored.
1000 Your program generally should not ignore signals that represent serious
1001 events or that are normally used to request termination.  You cannot
1002 ignore the @code{SIGKILL} or @code{SIGSTOP} signals at all.  You can
1003 ignore program error signals like @code{SIGSEGV}, but ignoring the error
1004 won't enable the program to continue executing meaningfully.  Ignoring
1005 user requests such as @code{SIGINT}, @code{SIGQUIT}, and @code{SIGTSTP}
1006 is unfriendly.
1008 When you do not wish signals to be delivered during a certain part of
1009 the program, the thing to do is to block them, not ignore them.
1010 @xref{Blocking Signals}.
1012 @item @var{handler}
1013 Supply the address of a handler function in your program, to specify
1014 running this handler as the way to deliver the signal.
1016 For more information about defining signal handler functions,
1017 see @ref{Defining Handlers}.
1018 @end table
1020 If you set the action for a signal to @code{SIG_IGN}, or if you set it
1021 to @code{SIG_DFL} and the default action is to ignore that signal, then
1022 any pending signals of that type are discarded (even if they are
1023 blocked).  Discarding the pending signals means that they will never be
1024 delivered, not even if you subsequently specify another action and
1025 unblock this kind of signal.
1027 The @code{signal} function returns the action that was previously in
1028 effect for the specified @var{signum}.  You can save this value and
1029 restore it later by calling @code{signal} again.
1031 If @code{signal} can't honor the request, it returns @code{SIG_ERR}
1032 instead.  The following @code{errno} error conditions are defined for
1033 this function:
1035 @table @code
1036 @item EINVAL
1037 You specified an invalid @var{signum}; or you tried to ignore or provide
1038 a handler for @code{SIGKILL} or @code{SIGSTOP}.
1039 @end table
1040 @end deftypefun
1042 Here is a simple example of setting up a handler to delete temporary
1043 files when certain fatal signals happen:
1045 @smallexample
1046 #include <signal.h>
1048 void
1049 termination_handler (int signum)
1051   struct temp_file *p;
1053   for (p = temp_file_list; p; p = p->next)
1054     unlink (p->name);
1058 main (void)
1060   @dots{}
1061   if (signal (SIGINT, termination_handler) == SIG_IGN)
1062     signal (SIGINT, SIG_IGN);
1063   if (signal (SIGHUP, termination_handler) == SIG_IGN)
1064     signal (SIGHUP, SIG_IGN);
1065   if (signal (SIGTERM, termination_handler) == SIG_IGN)
1066     signal (SIGTERM, SIG_IGN);
1067   @dots{}
1069 @end smallexample
1071 @noindent
1072 Note how if a given signal was previously set to be ignored, this code
1073 avoids altering that setting.  This is because non-job-control shells
1074 often ignore certain signals when starting children, and it is important
1075 for the children to respect this.
1077 We do not handle @code{SIGQUIT} or the program error signals in this
1078 example because these are designed to provide information for debugging
1079 (a core dump), and the temporary files may give useful information.
1081 @comment signal.h
1082 @comment SVID
1083 @deftypefun sighandler_t ssignal (int @var{signum}, sighandler_t @var{action})
1084 The @code{ssignal} function does the same thing as @code{signal}; it is
1085 provided only for compatibility with SVID.
1086 @end deftypefun
1088 @comment signal.h
1089 @comment ANSI
1090 @deftypevr Macro sighandler_t SIG_ERR
1091 The value of this macro is used as the return value from @code{signal}
1092 to indicate an error.
1093 @end deftypevr
1095 @ignore
1096 @comment RMS says that ``we don't do this''.
1097 Implementations might define additional macros for built-in signal
1098 actions that are suitable as a @var{action} argument to @code{signal},
1099 besides @code{SIG_IGN} and @code{SIG_DFL}.  Identifiers whose names
1100 begin with @samp{SIG_} followed by an uppercase letter are reserved for
1101 this purpose.
1102 @end ignore
1105 @node Advanced Signal Handling
1106 @subsection Advanced Signal Handling
1107 @cindex @code{sigaction} function
1109 The @code{sigaction} function has the same basic effect as
1110 @code{signal}: to specify how a signal should be handled by the process.
1111 However, @code{sigaction} offers more control, at the expense of more
1112 complexity.  In particular, @code{sigaction} allows you to specify
1113 additional flags to control when the signal is generated and how the
1114 handler is invoked.
1116 The @code{sigaction} function is declared in @file{signal.h}.
1117 @pindex signal.h
1119 @comment signal.h
1120 @comment POSIX.1
1121 @deftp {Data Type} {struct sigaction}
1122 Structures of type @code{struct sigaction} are used in the
1123 @code{sigaction} function to specify all the information about how to
1124 handle a particular signal.  This structure contains at least the
1125 following members:
1127 @table @code
1128 @item sighandler_t sa_handler
1129 This is used in the same way as the @var{action} argument to the
1130 @code{signal} function.  The value can be @code{SIG_DFL},
1131 @code{SIG_IGN}, or a function pointer.  @xref{Basic Signal Handling}.
1133 @item sigset_t sa_mask
1134 This specifies a set of signals to be blocked while the handler runs.
1135 Blocking is explained in @ref{Blocking for Handler}.  Note that the
1136 signal that was delivered is automatically blocked by default before its
1137 handler is started; this is true regardless of the value in
1138 @code{sa_mask}.  If you want that signal not to be blocked within its
1139 handler, you must write code in the handler to unblock it.
1141 @item int sa_flags
1142 This specifies various flags which can affect the behavior of 
1143 the signal.  These are described in more detail in @ref{Flags for Sigaction}.
1144 @end table
1145 @end deftp
1147 @comment signal.h
1148 @comment POSIX.1
1149 @deftypefun int sigaction (int @var{signum}, const struct sigaction *@var{action}, struct sigaction *@var{old-action})
1150 The @var{action} argument is used to set up a new action for the signal
1151 @var{signum}, while the @var{old-action} argument is used to return
1152 information about the action previously associated with this symbol.
1153 (In other words, @var{old-action} has the same purpose as the
1154 @code{signal} function's return value---you can check to see what the
1155 old action in effect for the signal was, and restore it later if you
1156 want.)
1158 Either @var{action} or @var{old-action} can be a null pointer.  If
1159 @var{old-action} is a null pointer, this simply suppresses the return
1160 of information about the old action.  If @var{action} is a null pointer,
1161 the action associated with the signal @var{signum} is unchanged; this
1162 allows you to inquire about how a signal is being handled without changing
1163 that handling.
1165 The return value from @code{sigaction} is zero if it succeeds, and
1166 @code{-1} on failure.  The following @code{errno} error conditions are
1167 defined for this function:
1169 @table @code
1170 @item EINVAL
1171 The @var{signum} argument is not valid, or you are trying to
1172 trap or ignore @code{SIGKILL} or @code{SIGSTOP}.
1173 @end table
1174 @end deftypefun
1176 @node Signal and Sigaction
1177 @subsection Interaction of @code{signal} and @code{sigaction}
1179 It's possible to use both the @code{signal} and @code{sigaction}
1180 functions within a single program, but you have to be careful because
1181 they can interact in slightly strange ways.
1183 The @code{sigaction} function specifies more information than the
1184 @code{signal} function, so the return value from @code{signal} cannot
1185 express the full range of @code{sigaction} possibilities.  Therefore, if
1186 you use @code{signal} to save and later reestablish an action, it may
1187 not be able to reestablish properly a handler that was established with
1188 @code{sigaction}.
1190 To avoid having problems as a result, always use @code{sigaction} to
1191 save and restore a handler if your program uses @code{sigaction} at all.
1192 Since @code{sigaction} is more general, it can properly save and
1193 reestablish any action, regardless of whether it was established
1194 originally with @code{signal} or @code{sigaction}.
1196 On some systems if you establish an action with @code{signal} and then
1197 examine it with @code{sigaction}, the handler address that you get may
1198 not be the same as what you specified with @code{signal}.  It may not
1199 even be suitable for use as an action argument with @code{signal}.  But
1200 you can rely on using it as an argument to @code{sigaction}.  This
1201 problem never happens on the GNU system.
1203 So, you're better off using one or the other of the mechanisms
1204 consistently within a single program.  
1206 @strong{Portability Note:} The basic @code{signal} function is a feature
1207 of ANSI C, while @code{sigaction} is part of the POSIX.1 standard.  If
1208 you are concerned about portability to non-POSIX systems, then you
1209 should use the @code{signal} function instead.
1211 @node Sigaction Function Example
1212 @subsection @code{sigaction} Function Example
1214 In @ref{Basic Signal Handling}, we gave an example of establishing a
1215 simple handler for termination signals using @code{signal}.  Here is an
1216 equivalent example using @code{sigaction}:
1218 @smallexample
1219 #include <signal.h>
1221 void
1222 termination_handler (int signum)
1224   struct temp_file *p;
1226   for (p = temp_file_list; p; p = p->next)
1227     unlink (p->name);
1231 main (void)
1233   @dots{}
1234   struct sigaction new_action, old_action;
1236   /* @r{Set up the structure to specify the new action.} */
1237   new_action.sa_handler = termination_handler;
1238   sigemptyset (&new_action.sa_mask);
1239   new_action.sa_flags = 0;
1241   sigaction (SIGINT, NULL, &old_action);
1242   if (old_action.sa_handler != SIG_IGN)
1243     sigaction (SIGINT, &new_action, NULL);
1244   sigaction (SIGHUP, NULL, &old_action);
1245   if (old_action.sa_handler != SIG_IGN)
1246     sigaction (SIGHUP, &new_action, NULL);
1247   sigaction (SIGTERM, NULL, &old_action);
1248   if (old_action.sa_handler != SIG_IGN)
1249     sigaction (SIGTERM, &new_action, NULL);
1250   @dots{}
1252 @end smallexample
1254 The program just loads the @code{new_action} structure with the desired
1255 parameters and passes it in the @code{sigaction} call.  The usage of
1256 @code{sigemptyset} is described later; see @ref{Blocking Signals}.
1258 As in the example using @code{signal}, we avoid handling signals
1259 previously set to be ignored.  Here we can avoid altering the signal
1260 handler even momentarily, by using the feature of @code{sigaction} that
1261 lets us examine the current action without specifying a new one.
1263 Here is another example.  It retrieves information about the current
1264 action for @code{SIGINT} without changing that action.
1266 @smallexample
1267 struct sigaction query_action;
1269 if (sigaction (SIGINT, NULL, &query_action) < 0)
1270   /* @r{@code{sigaction} returns -1 in case of error.} */ 
1271 else if (query_action.sa_handler == SIG_DFL)
1272   /* @r{@code{SIGINT} is handled in the default, fatal manner.} */
1273 else if (query_action.sa_handler == SIG_IGN)
1274   /* @r{@code{SIGINT} is ignored.} */
1275 else
1276   /* @r{A programmer-defined signal handler is in effect.} */
1277 @end smallexample
1279 @node Flags for Sigaction
1280 @subsection Flags for @code{sigaction}
1281 @cindex signal flags
1282 @cindex flags for @code{sigaction}
1283 @cindex @code{sigaction} flags
1285 The @code{sa_flags} member of the @code{sigaction} structure is a
1286 catch-all for special features.  Most of the time, @code{SA_RESTART} is
1287 a good value to use for this field.
1289 The value of @code{sa_flags} is interpreted as a bit mask.  Thus, you
1290 should choose the flags you want to set, @sc{or} those flags together,
1291 and store the result in the @code{sa_flags} member of your
1292 @code{sigaction} structure.
1294 Each signal number has its own set of flags.  Each call to
1295 @code{sigaction} affects one particular signal number, and the flags
1296 that you specify apply only to that particular signal.
1298 In the GNU C library, establishing a handler with @code{signal} sets all
1299 the flags to zero except for @code{SA_RESTART}, whose value depends on
1300 the settings you have made with @code{siginterrupt}.  @xref{Interrupted
1301 Primitives}, to see what this is about.
1303 @pindex signal.h
1304 These macros are defined in the header file @file{signal.h}.
1306 @comment signal.h
1307 @comment POSIX.1
1308 @deftypevr Macro int SA_NOCLDSTOP
1309 This flag is meaningful only for the @code{SIGCHLD} signal.  When the
1310 flag is set, the system delivers the signal for a terminated child
1311 process but not for one that is stopped.  By default, @code{SIGCHLD} is
1312 delivered for both terminated children and stopped children.
1314 Setting this flag for a signal other than @code{SIGCHLD} has no effect.
1315 @end deftypevr
1317 @comment signal.h
1318 @comment BSD
1319 @deftypevr Macro int SA_ONSTACK
1320 If this flag is set for a particular signal number, the system uses the
1321 signal stack when delivering that kind of signal.  @xref{Signal Stack}.
1322 If a signal with this flag arrives and you have not set a signal stack,
1323 the system terminates the program with @code{SIGILL}.
1324 @end deftypevr
1326 @comment signal.h
1327 @comment BSD
1328 @deftypevr Macro int SA_RESTART
1329 This flag controls what happens when a signal is delivered during
1330 certain primitives (such as @code{open}, @code{read} or @code{write}),
1331 and the signal handler returns normally.  There are two alternatives:
1332 the library function can resume, or it can return failure with error
1333 code @code{EINTR}.
1335 The choice is controlled by the @code{SA_RESTART} flag for the
1336 particular kind of signal that was delivered.  If the flag is set,
1337 returning from a handler resumes the library function.  If the flag is
1338 clear, returning from a handler makes the function fail.
1339 @xref{Interrupted Primitives}.
1340 @end deftypevr
1342 @node Initial Signal Actions
1343 @subsection Initial Signal Actions
1344 @cindex initial signal actions
1346 When a new process is created (@pxref{Creating a Process}), it inherits
1347 handling of signals from its parent process.  However, when you load a
1348 new process image using the @code{exec} function (@pxref{Executing a
1349 File}), any signals that you've defined your own handlers for revert to
1350 their @code{SIG_DFL} handling.  (If you think about it a little, this
1351 makes sense; the handler functions from the old program are specific to
1352 that program, and aren't even present in the address space of the new
1353 program image.)  Of course, the new program can establish its own
1354 handlers.
1356 When a program is run by a shell, the shell normally sets the initial
1357 actions for the child process to @code{SIG_DFL} or @code{SIG_IGN}, as
1358 appropriate.  It's a good idea to check to make sure that the shell has
1359 not set up an initial action of @code{SIG_IGN} before you establish your
1360 own signal handlers.
1362 Here is an example of how to establish a handler for @code{SIGHUP}, but
1363 not if @code{SIGHUP} is currently ignored:
1365 @smallexample
1366 @group
1367 @dots{}
1368 struct sigaction temp;
1370 sigaction (SIGHUP, NULL, &temp);
1372 if (temp.sa_handler != SIG_IGN)
1373   @{
1374     temp.sa_handler = handle_sighup;
1375     sigemptyset (&temp.sa_mask);
1376     sigaction (SIGHUP, &temp, NULL);
1377   @}
1378 @end group
1379 @end smallexample
1381 @node Defining Handlers
1382 @section Defining Signal Handlers
1383 @cindex signal handler function
1385 This section describes how to write a signal handler function that can
1386 be established with the @code{signal} or @code{sigaction} functions.
1388 A signal handler is just a function that you compile together with the
1389 rest of the program.  Instead of directly invoking the function, you use
1390 @code{signal} or @code{sigaction} to tell the operating system to call
1391 it when a signal arrives.  This is known as @dfn{establishing} the
1392 handler.  @xref{Signal Actions}.
1394 There are two basic strategies you can use in signal handler functions:
1396 @itemize @bullet
1397 @item
1398 You can have the handler function note that the signal arrived by
1399 tweaking some global data structures, and then return normally.
1401 @item
1402 You can have the handler function terminate the program or transfer
1403 control to a point where it can recover from the situation that caused
1404 the signal.
1405 @end itemize
1407 You need to take special care in writing handler functions because they
1408 can be called asynchronously.  That is, a handler might be called at any
1409 point in the program, unpredictably.  If two signals arrive during a
1410 very short interval, one handler can run within another.  This section
1411 describes what your handler should do, and what you should avoid.
1413 @menu
1414 * Handler Returns::             Handlers that return normally, and what
1415                                  this means. 
1416 * Termination in Handler::      How handler functions terminate a program.
1417 * Longjmp in Handler::          Nonlocal transfer of control out of a
1418                                  signal handler.
1419 * Signals in Handler::          What happens when signals arrive while
1420                                  the handler is already occupied.
1421 * Merged Signals::              When a second signal arrives before the
1422                                  first is handled.
1423 * Nonreentrancy::               Do not call any functions unless you know they
1424                                  are reentrant with respect to signals. 
1425 * Atomic Data Access::          A single handler can run in the middle of
1426                                  reading or writing a single object. 
1427 @end menu
1429 @node Handler Returns
1430 @subsection Signal Handlers that Return
1432 Handlers which return normally are usually used for signals such as
1433 @code{SIGALRM} and the I/O and interprocess communication signals.  But
1434 a handler for @code{SIGINT} might also return normally after setting a
1435 flag that tells the program to exit at a convenient time.
1437 It is not safe to return normally from the handler for a program error
1438 signal, because the behavior of the program when the handler function
1439 returns is not defined after a program error.  @xref{Program Error
1440 Signals}.
1442 Handlers that return normally must modify some global variable in order
1443 to have any effect.  Typically, the variable is one that is examined
1444 periodically by the program during normal operation.  Its data type
1445 should be @code{sig_atomic_t} for reasons described in @ref{Atomic
1446 Data Access}.
1448 Here is a simple example of such a program.  It executes the body of
1449 the loop until it has noticed that a @code{SIGALRM} signal has arrived.
1450 This technique is useful because it allows the iteration in progress
1451 when the signal arrives to complete before the loop exits.
1453 @smallexample
1454 @include sigh1.c.texi
1455 @end smallexample
1457 @node Termination in Handler
1458 @subsection Handlers That Terminate the Process
1460 Handler functions that terminate the program are typically used to cause
1461 orderly cleanup or recovery from program error signals and interactive
1462 interrupts.
1464 The cleanest way for a handler to terminate the process is to raise the
1465 same signal that ran the handler in the first place.  Here is how to do
1466 this:
1468 @smallexample
1469 volatile sig_atomic_t fatal_error_in_progress = 0;
1471 void
1472 fatal_error_signal (int sig)
1474 @group
1475   /* @r{Since this handler is established for more than one kind of signal, }
1476      @r{it might still get invoked recursively by delivery of some other kind}
1477      @r{of signal.  Use a static variable to keep track of that.} */
1478   if (fatal_error_in_progress)
1479     raise (sig);
1480   fatal_error_in_progress = 1;
1481 @end group
1483 @group
1484   /* @r{Now do the clean up actions:}
1485      @r{- reset terminal modes}
1486      @r{- kill child processes}
1487      @r{- remove lock files} */
1488   @dots{}
1489 @end group
1491 @group
1492   /* @r{Now reraise the signal.  Since the signal is blocked,}
1493      @r{it will receive its default handling, which is}
1494      @r{to terminate the process.  We could just call}
1495      @r{@code{exit} or @code{abort}, but reraising the signal}
1496      @r{sets the return status from the process correctly.} */
1497   raise (sig);
1499 @end group
1500 @end smallexample
1502 @node Longjmp in Handler
1503 @subsection Nonlocal Control Transfer in Handlers
1504 @cindex non-local exit, from signal handler
1506 You can do a nonlocal transfer of control out of a signal handler using
1507 the @code{setjmp} and @code{longjmp} facilities (@pxref{Non-Local
1508 Exits}).
1510 When the handler does a nonlocal control transfer, the part of the
1511 program that was running will not continue.  If this part of the program
1512 was in the middle of updating an important data structure, the data
1513 structure will remain inconsistent.  Since the program does not
1514 terminate, the inconsistency is likely to be noticed later on.
1516 There are two ways to avoid this problem.  One is to block the signal
1517 for the parts of the program that update important data structures.
1518 Blocking the signal delays its delivery until it is unblocked, once the
1519 critical updating is finished.  @xref{Blocking Signals}.
1521 The other way to re-initialize the crucial data structures in the signal
1522 handler, or make their values consistent.
1524 Here is a rather schematic example showing the reinitialization of one
1525 global variable.
1527 @smallexample
1528 @group
1529 #include <signal.h>
1530 #include <setjmp.h>
1532 jmp_buf return_to_top_level;
1534 volatile sig_atomic_t waiting_for_input;
1536 void
1537 handle_sigint (int signum)
1539   /* @r{We may have been waiting for input when the signal arrived,}
1540      @r{but we are no longer waiting once we transfer control.} */
1541   waiting_for_input = 0;
1542   longjmp (return_to_top_level, 1);
1544 @end group
1546 @group
1548 main (void)
1550   @dots{}
1551   signal (SIGINT, sigint_handler);
1552   @dots{}
1553   while (1) @{
1554     prepare_for_command ();
1555     if (setjmp (return_to_top_level) == 0)
1556       read_and_execute_command ();
1557   @}
1559 @end group
1561 @group
1562 /* @r{Imagine this is a subroutine used by various commands.} */
1563 char *
1564 read_data ()
1566   if (input_from_terminal) @{
1567     waiting_for_input = 1;
1568     @dots{}
1569     waiting_for_input = 0;
1570   @} else @{ 
1571     @dots{}
1572   @}
1574 @end group
1575 @end smallexample
1578 @node Signals in Handler
1579 @subsection Signals Arriving While a Handler Runs
1580 @cindex race conditions, relating to signals
1582 What happens if another signal arrives while your signal handler
1583 function is running?
1585 When the handler for a particular signal is invoked, that signal is
1586 automatically blocked until the handler returns.  That means that if two
1587 signals of the same kind arrive close together, the second one will be
1588 held until the first has been handled.  (The handler can explicitly
1589 unblock the signal using @code{sigprocmask}, if you want to allow more
1590 signals of this type to arrive; see @ref{Process Signal Mask}.)
1592 However, your handler can still be interrupted by delivery of another
1593 kind of signal.  To avoid this, you can use the @code{sa_mask} member of
1594 the action structure passed to @code{sigaction} to explicitly specify
1595 which signals should be blocked while the signal handler runs.  These
1596 signals are in addition to the signal for which the handler was invoked,
1597 and any other signals that are normally blocked by the process.
1598 @xref{Blocking for Handler}.
1600 When the handler returns, the set of blocked signals is restored to the
1601 value it had before the handler ran.  So using @code{sigprocmask} inside
1602 the handler only affects what signals can arrive during the execution of
1603 the handler itself, not what signals can arrive once the handler returns.
1605 @strong{Portability Note:} Always use @code{sigaction} to establish a
1606 handler for a signal that you expect to receive asynchronously, if you
1607 want your program to work properly on System V Unix.  On this system,
1608 the handling of a signal whose handler was established with
1609 @code{signal} automatically sets the signal's action back to
1610 @code{SIG_DFL}, and the handler must re-establish itself each time it
1611 runs.  This practice, while inconvenient, does work when signals cannot
1612 arrive in succession.  However, if another signal can arrive right away,
1613 it may arrive before the handler can re-establish itself.  Then the
1614 second signal would receive the default handling, which could terminate
1615 the process.
1617 @node Merged Signals
1618 @subsection Signals Close Together Merge into One
1619 @cindex handling multiple signals
1620 @cindex successive signals
1621 @cindex merging of signals
1623 If multiple signals of the same type are delivered to your process
1624 before your signal handler has a chance to be invoked at all, the
1625 handler may only be invoked once, as if only a single signal had
1626 arrived.  In effect, the signals merge into one.  This situation can
1627 arise when the signal is blocked, or in a multiprocessing environment
1628 where the system is busy running some other processes while the signals
1629 are delivered.  This means, for example, that you cannot reliably use a
1630 signal handler to count signals.  The only distinction you can reliably
1631 make is whether at least one signal has arrived since a given time in
1632 the past.
1634 Here is an example of a handler for @code{SIGCHLD} that compensates for
1635 the fact that the number of signals recieved may not equal the number of
1636 child processes generate them.  It assumes that the program keeps track
1637 of all the child processes with a chain of structures as follows:
1639 @smallexample
1640 struct process
1642   struct process *next;
1643   /* @r{The process ID of this child.}  */
1644   int pid;
1645   /* @r{The descriptor of the pipe or pseudo terminal}
1646      @r{on which output comes from this child.}  */
1647   int input_descriptor;
1648   /* @r{Nonzero if this process has stopped or terminated.}  */
1649   sig_atomic_t have_status;
1650   /* @r{The status of this child; 0 if running,}
1651      @r{otherwise a status value from @code{waitpid}.}  */
1652   int status;
1655 struct process *process_list;
1656 @end smallexample
1658 This example also uses a flag to indicate whether signals have arrived
1659 since some time in the past---whenever the program last cleared it to
1660 zero.
1662 @smallexample
1663 /* @r{Nonzero means some child's status has changed}
1664    @r{so look at @code{process_list} for the details.}  */
1665 int process_status_change;
1666 @end smallexample
1668 Here is the handler itself:
1670 @smallexample
1671 void
1672 sigchld_handler (int signo)
1674   int old_errno = errno;
1676   while (1) @{
1677     register int pid;
1678     int w;
1679     struct process *p;
1681     /* @r{Keep asking for a status until we get a definitive result.}  */
1682     do 
1683       @{
1684         errno = 0;
1685         pid = waitpid (WAIT_ANY, &w, WNOHANG | WUNTRACED);
1686       @}
1687     while (pid <= 0 && errno == EINTR);
1689     if (pid <= 0) @{
1690       /* @r{A real failure means there are no more}
1691          @r{stopped or terminated child processes, so return.}  */
1692       errno = old_errno;
1693       return;
1694     @}
1696     /* @r{Find the process that signaled us, and record its status.}  */
1698     for (p = process_list; p; p = p->next)
1699       if (p->pid == pid) @{
1700         p->status = w;
1701         /* @r{Indicate that the @code{status} field}
1702            @r{has data to look at.  We do this only after storing it.}  */
1703         p->have_status = 1;
1705         /* @r{If process has terminated, stop waiting for its output.}  */
1706         if (WIFSIGNALED (w) || WIFEXITED (w))
1707           if (p->input_descriptor)
1708             FD_CLR (p->input_descriptor, &input_wait_mask);
1710         /* @r{The program should check this flag from time to time}
1711            @r{to see if there is any news in @code{process_list}.}  */
1712         ++process_status_change;
1713       @}
1715     /* @r{Loop around to handle all the processes}
1716        @r{that have something to tell us.}  */
1717   @}
1719 @end smallexample
1721 Here is the proper way to check the flag @code{process_status_change}:
1723 @smallexample
1724 if (process_status_change) @{
1725   struct process *p;
1726   process_status_change = 0;
1727   for (p = process_list; p; p = p->next)
1728     if (p->have_status) @{
1729       @dots{} @r{Examine @code{p->status}} @dots{}
1730     @}
1732 @end smallexample
1734 @noindent
1735 It is vital to clear the flag before examining the list; otherwise, if a
1736 signal were delivered just before the clearing of the flag, and after
1737 the appropriate element of the process list had been checked, the status
1738 change would go unnoticed until the next signal arrived to set the flag
1739 again.  You could, of course, avoid this problem by blocking the signal
1740 while scanning the list, but it is much more elegant to guarantee
1741 correctness by doing things in the right order.
1743 The loop which checks process status avoids examining @code{p->status}
1744 until it sees that status has been validly stored.  This is to make sure
1745 that the status cannot change in the middle of accessing it.  Once
1746 @code{p->have_status} is set, it means that the child process is stopped
1747 or terminated, and in either case, it cannot stop or terminate again
1748 until the program has taken notice.  @xref{Atomic Usage}, for more
1749 information about coping with interruptions during accessings of a
1750 variable.
1752 Here is another way you can test whether the handler has run since the
1753 last time you checked.  This technique uses a counter which is never
1754 changed outside the handler.  Instead of clearing the count, the program
1755 remembers the previous value and sees whether it has changed since the
1756 previous check.  The advantage of this method is that different parts of
1757 the program can check independently, each part checking whether there
1758 has been a signal since that part last checked.
1760 @smallexample
1761 sig_atomic_t process_status_change;
1763 sig_atomic_t last_process_status_change;
1765 @dots{}
1767   sig_atomic_t prev = last_process_status_change;
1768   last_process_status_change = process_status_change;
1769   if (last_process_status_change != prev) @{
1770     struct process *p;
1771     for (p = process_list; p; p = p->next)
1772       if (p->have_status) @{
1773         @dots{} @r{Examine @code{p->status}} @dots{}
1774       @}
1775   @}
1777 @end smallexample
1779 @node Nonreentrancy
1780 @subsection Signal Handling and Nonreentrant Functions 
1781 @cindex restrictions on signal handler functions
1783 Handler functions usually don't do very much.  The best practice is to
1784 write a handler that does nothing but set an external variable that the
1785 program checks regularly, and leave all serious work to the program.
1786 This is best because the handler can be called at asynchronously, at
1787 unpredictable times---perhaps in the middle of a primitive function, or
1788 even between the beginning and the end of a C operator that requires
1789 multiple instructions.  The data structures being manipulated might
1790 therefore be in an inconsistent state when the handler function is
1791 invoked.  Even copying one @code{int} variable into another can take two
1792 instructions on most machines.
1794 This means you have to be very careful about what you do in a signal
1795 handler.
1797 @itemize @bullet
1798 @item
1799 @cindex @code{volatile} declarations
1800 If your handler needs to access any global variables from your program,
1801 declare those variables @code{volatile}.  This tells the compiler that
1802 the value of the variable might change asynchronously, and inhibits
1803 certain optimizations that would be invalidated by such modifications.
1805 @item
1806 @cindex reentrant functions
1807 If you call a function in the handler, make sure it is @dfn{reentrant}
1808 with respect to signals, or else make sure that the signal cannot
1809 interrupt a call to a related function.
1810 @end itemize
1812 A function can be non-reentrant if it uses memory that is not on the
1813 stack.
1815 @itemize @bullet
1816 @item
1817 If a function uses a static variable or a global variable, or a
1818 dynamically-allocated object that it finds for itself, then it is
1819 non-reentrant and any two calls to the function can interfere.
1821 For example, suppose that the signal handler uses @code{gethostbyname}.
1822 This function returns its value in a static object, reusing the same
1823 object each time.  If the signal happens to arrive during a call to
1824 @code{gethostbyname}, or even after one (while the program is still
1825 using the value), it will clobber the value that the program asked for.
1827 However, if the program does not use @code{gethostbyname} or any other
1828 function that returns information in the same object, or if it always
1829 blocks signals around each use, then you are safe.
1831 There are a large number of library functions that return values in a
1832 fixed object, always reusing the same object in this fashion, and all of
1833 them cause the same problem.  The description of a function in this
1834 manual always mentions this behavior.
1836 @item
1837 If a function uses and modifies an object that you supply, then it is
1838 potentially non-reentrant; two calls can interfere if they use the same
1839 object.
1841 This case arises when you do I/O using streams.  Suppose that the
1842 signal handler prints a message with @code{fprintf}.  Suppose that the
1843 program was in the middle of an @code{fprintf} call using the same
1844 stream when the signal was delivered.  Both the signal handler's message
1845 and the program's data could be corrupted, because both calls operate on
1846 the same data structure---the stream itself.
1848 However, if you know that the stream that the handler uses cannot
1849 possibly be used by the program at a time when signals can arrive, then
1850 you are safe.  It is no problem if the program uses some other stream.
1852 @item
1853 On most systems, @code{malloc} and @code{free} are not reentrant,
1854 because they use a static data structure which records what memory
1855 blocks are free.  As a result, no library functions that allocate or
1856 free memory are reentrant.  This includes functions that allocate space
1857 to store a result.
1859 The best way to avoid the need to allocate memory in a handler is to
1860 allocate in advance space for signal handlers to use.
1862 The best way to avoid freeing memory in a handler is to flag or record
1863 the objects to be freed, and have the program check from time to time
1864 whether anything is waiting to be freed.  But this must be done with
1865 care, because placing an object on a chain is not atomic, and if it is
1866 interrupted by another signal handler that does the same thing, you
1867 could ``lose'' one of the objects.
1869 @ignore
1870 !!! not true
1871 On the GNU system, @code{malloc} and @code{free} are safe to use in
1872 signal handlers because they block signals.  As a result, the library
1873 functions that allocate space for a result are also safe in signal
1874 handlers.  The obstack allocation functions are safe as long as you
1875 don't use the same obstack both inside and outside of a signal handler.
1876 @end ignore
1878 The relocating allocation functions (@pxref{Relocating Allocator})
1879 are certainly not safe to use in a signal handler.
1881 @item
1882 Any function that modifies @code{errno} is non-reentrant, but you can
1883 correct for this: in the handler, save the original value of
1884 @code{errno} and restore it before returning normally.  This prevents
1885 errors that occur within the signal handler from being confused with
1886 errors from system calls at the point the program is interrupted to run
1887 the handler.
1889 This technique is generally applicable; if you want to call in a handler
1890 a function that modifies a particular object in memory, you can make
1891 this safe by saving and restoring that object.
1893 @item
1894 Merely reading from a memory object is safe provided that you can deal
1895 with any of the values that might appear in the object at a time when
1896 the signal can be delivered.  Keep in mind that assignment to some data
1897 types requires more than one instruction, which means that the handler
1898 could run ``in the middle of'' an assignment to the variable if its type
1899 is not atomic.  @xref{Atomic Data Access}.
1901 @item
1902 Merely writing into a memory object is safe as long as a sudden change
1903 in the value, at any time when the handler might run, will not disturb
1904 anything.
1905 @end itemize
1907 @node Atomic Data Access
1908 @subsection Atomic Data Access and Signal Handling
1910 Whether the data in your application concerns atoms, or mere text, you
1911 have to be careful about the fact that access to a single datum is not
1912 necessarily @dfn{atomic}.  This means that it can take more than one
1913 instruction to read or write a single object.  In such cases, a signal
1914 handler might in the middle of reading or writing the object.
1916 There are three ways you can cope with this problem.  You can use data
1917 types that are always accessed atomically; you can carefully arrange
1918 that nothing untoward happens if an access is interrupted, or you can
1919 block all signals around any access that had better not be interrupted
1920 (@pxref{Blocking Signals}).
1922 @menu
1923 * Non-atomic Example::          A program illustrating interrupted access.
1924 * Types: Atomic Types.          Data types that guarantee no interruption.
1925 * Usage: Atomic Usage.          Proving that interruption is harmless.
1926 @end menu
1928 @node Non-atomic Example
1929 @subsubsection Problems with Non-Atomic Access
1931 Here is an example which shows what can happen if a signal handler runs
1932 in the middle of modifying a variable.  (Interrupting the reading of a
1933 variable can also lead to paradoxical results, but here we only show
1934 writing.)
1936 @smallexample
1937 #include <signal.h>
1938 #include <stdio.h>
1940 struct two_words @{ int a, b; @} memory;
1942 void
1943 handler(int signum)
1945    printf ("%d,%d\n", memory.a, memory.b);
1946    alarm (1);
1949 @group
1951 main (void)
1953    static struct two_words zeros = @{ 0, 0 @}, ones = @{ 1, 1 @};
1954    signal (SIGALRM, handler);
1955    memory = zeros;
1956    alarm (1);
1957    while (1)
1958      @{
1959        memory = zeros;
1960        memory = ones;
1961      @}
1963 @end group
1964 @end smallexample
1966 This program fills @code{memory} with zeros, ones, zeros, ones,
1967 alternating forever; meanwhile, once per second, the alarm signal handler
1968 prints the current contents.  (Calling @code{printf} in the handler is
1969 safe in this program because it is certainly not being called outside
1970 the handler when the signal happens.)
1972 Clearly, this program can print a pair of zeros or a pair of ones.  But
1973 that's not all it can do!  On most machines, it takes several
1974 instructions to store a new value in @code{memory}, and the value is
1975 stored one word at a time.  If the signal is delivered in between these
1976 instructions, the handler might find that @code{memory.a} is zero and
1977 @code{memory.b} is one (or vice versa).
1979 On some machines it may be possible to store a new value in
1980 @code{memory} with just one instruction that cannot be interrupted.  On
1981 these machines, the handler will always print two zeros or two ones.
1983 @node Atomic Types
1984 @subsubsection Atomic Types
1986 To avoid uncertainty about interrupting access to a variable, you can
1987 use a particular data type for which access is always atomic:
1988 @code{sig_atomic_t}.  Reading and writing this data type is guaranteed
1989 to happen in a single instruction, so there's no way for a handler to
1990 run ``in the middle'' of an access.
1992 The type @code{sig_atomic_t} is always an integer data type, but which
1993 one it is, and how many bits it contains, may vary from machine to
1994 machine.
1996 @comment signal.h
1997 @comment ANSI
1998 @deftp {Data Type} sig_atomic_t
1999 This is an integer data type.  Objects of this type are always accessed
2000 atomically.
2001 @end deftp
2003 In practice, you can assume that @code{int} and other integer types no
2004 longer than @code{int} are atomic.  You can also assume that pointer
2005 types are atomic; that is very convenient.  Both of these are true on
2006 all of the machines that the GNU C library supports, and on all POSIX
2007 systems we know of.
2008 @c ??? This might fail on a 386 that uses 64-bit pointers.
2010 @node Atomic Usage
2011 @subsubsection Atomic Usage Patterns
2013 Certain patterns of access avoid any problem even if an access is
2014 interrupted.  For example, a flag which is set by the handler, and
2015 tested and cleared by the main program from time to time, is always safe
2016 even if access actually requires two instructions.  To show that this is
2017 so, we must consider each access that could be interrupted, and show
2018 that there is no problem if it is interrupted.
2020 An interrupt in the middle of testing the flag is safe because either it's
2021 recognized to be nonzero, in which case the precise value doesn't
2022 matter, or it will be seen to be nonzero the next time it's tested.
2024 An interrupt in the middle of clearing the flag is no problem because
2025 either the value ends up zero, which is what happens if a signal comes
2026 in just before the flag is cleared, or the value ends up nonzero, and
2027 subsequent events occur as if the signal had come in just after the flag
2028 was cleared.  As long as the code handles both of these cases properly,
2029 it can also handle a signal in the middle of clearing the flag.  (This
2030 is an example of the sort of reasoning you need to do to figure out
2031 whether non-atomic usage is safe.)
2033 Sometimes you can insure uninterrupted access to one object by
2034 protecting its use with another object, perhaps one whose type
2035 guarantees atomicity.  @xref{Merged Signals}, for an example.
2037 @node Interrupted Primitives
2038 @section Primitives Interrupted by Signals
2040 A signal can arrive and be handled while an I/O primitive such as
2041 @code{open} or @code{read} is waiting for an I/O device.  If the signal
2042 handler returns, the system faces the question: what should happen next?
2044 POSIX specifies one approach: make the primitive fail right away.  The
2045 error code for this kind of failure is @code{EINTR}.  This is flexible,
2046 but usually inconvenient.  Typically, POSIX applications that use signal
2047 handlers must check for @code{EINTR} after each library function that
2048 can return it, in order to try the call again.  Often programmers forget
2049 to check, which is a common source of error.
2051 The GNU library provides a convenient way to retry a call after a
2052 temporary failure, with the macro @code{TEMP_FAILURE_RETRY}:
2054 @comment unistd.h
2055 @comment GNU
2056 @defmac TEMP_FAILURE_RETRY (@var{expression})
2057 This macro evaluates @var{expression} once.  If it fails and reports
2058 error code @code{EINTR}, @code{TEMP_FAILURE_RETRY} evaluates it again,
2059 and over and over until the result is not a temporary failure.
2061 The value returned by @code{TEMP_FAILURE_RETRY} is whatever value
2062 @var{expression} produced.
2063 @end defmac
2065 BSD avoids @code{EINTR} entirely and provides a more convenient
2066 approach: to restart the interrupted primitive, instead of making it
2067 fail.  If you choose this approach, you need not be concerned with
2068 @code{EINTR}.
2070 You can choose either approach with the GNU library.  If you use
2071 @code{sigaction} to establish a signal handler, you can specify how that
2072 handler should behave.  If you specify the @code{SA_RESTART} flag,
2073 return from that handler will resume a primitive; otherwise, return from
2074 that handler will cause @code{EINTR}.  @xref{Flags for Sigaction}.
2076 Another way to specify the choice is with the @code{siginterrupt}
2077 function.  @xref{BSD Handler}.
2079 @c !!! not true now about _BSD_SOURCE
2080 When you don't specify with @code{sigaction} or @code{siginterrupt} what
2081 a particular handler should do, it uses a default choice.  The default
2082 choice in the GNU library depends on the feature test macros you have
2083 defined.  If you define @code{_BSD_SOURCE} or @code{_GNU_SOURCE} before
2084 calling @code{signal}, the default is to resume primitives; otherwise,
2085 the default is to make them fail with @code{EINTR}.  (The library
2086 contains alternate versions of the @code{signal} function, and the
2087 feature test macros determine which one you really call.)  @xref{Feature
2088 Test Macros}.
2089 @cindex EINTR, and restarting interrupted primitives
2090 @cindex restarting interrupted primitives
2091 @cindex interrupting primitives
2092 @cindex primitives, interrupting
2093 @c !!! want to have @cindex system calls @i{see} primitives [no page #]
2095 The description of each primitive affected by this issue
2096 lists @code{EINTR} among the error codes it can return.
2098 There is one situation where resumption never happens no matter which
2099 choice you make: when a data-transfer function such as @code{read} or
2100 @code{write} is interrupted by a signal after transferring part of the
2101 data.  In this case, the function returns the number of bytes already
2102 transferred, indicating partial success.
2104 This might at first appear to cause unreliable behavior on
2105 record-oriented devices (including datagram sockets; @pxref{Datagrams}),
2106 where splitting one @code{read} or @code{write} into two would read or
2107 write two records.  Actually, there is no problem, because interruption
2108 after a partial transfer cannot happen on such devices; they always
2109 transfer an entire record in one burst, with no waiting once data
2110 transfer has started.
2112 @node Generating Signals
2113 @section Generating Signals
2114 @cindex sending signals
2115 @cindex raising signals
2116 @cindex signals, generating
2118 Besides signals that are generated as a result of a hardware trap or
2119 interrupt, your program can explicitly send signals to itself or to
2120 another process.
2122 @menu
2123 * Signaling Yourself::          A process can send a signal to itself.
2124 * Signaling Another Process::   Send a signal to another process.
2125 * Permission for kill::         Permission for using @code{kill}.
2126 * Kill Example::                Using @code{kill} for Communication.
2127 @end menu
2129 @node Signaling Yourself
2130 @subsection Signaling Yourself
2132 A process can send itself a signal with the @code{raise} function.  This
2133 function is declared in @file{signal.h}.
2134 @pindex signal.h
2136 @comment signal.h
2137 @comment ANSI
2138 @deftypefun int raise (int @var{signum})
2139 The @code{raise} function sends the signal @var{signum} to the calling
2140 process.  It returns zero if successful and a nonzero value if it fails.
2141 About the only reason for failure would be if the value of @var{signum}
2142 is invalid.
2143 @end deftypefun
2145 @comment signal.h
2146 @comment SVID
2147 @deftypefun int gsignal (int @var{signum})
2148 The @code{gsignal} function does the same thing as @code{raise}; it is
2149 provided only for compatibility with SVID.
2150 @end deftypefun
2152 One convenient use for @code{raise} is to reproduce the default behavior
2153 of a signal that you have trapped.  For instance, suppose a user of your
2154 program types the SUSP character (usually @kbd{C-z}; @pxref{Special
2155 Characters}) to send it an interactive stop stop signal
2156 (@code{SIGTSTP}), and you want to clean up some internal data buffers
2157 before stopping.  You might set this up like this:
2159 @comment RMS suggested getting rid of the handler for SIGCONT in this function.
2160 @comment But that would require that the handler for SIGTSTP unblock the
2161 @comment signal before doing the call to raise.  We haven't covered that
2162 @comment topic yet, and I don't want to distract from the main point of
2163 @comment the example with a digression to explain what is going on.  As
2164 @comment the example is written, the signal that is raise'd will be delivered
2165 @comment as soon as the SIGTSTP handler returns, which is fine.
2167 @smallexample
2168 #include <signal.h>
2170 /* @r{When a stop signal arrives, set the action back to the default
2171    and then resend the signal after doing cleanup actions.} */
2173 void
2174 tstp_handler (int sig)
2176   signal (SIGTSTP, SIG_DFL);
2177   /* @r{Do cleanup actions here.} */
2178   @dots{}
2179   raise (SIGTSTP);
2182 /* @r{When the process is continued again, restore the signal handler.} */
2184 void
2185 cont_handler (int sig)
2187   signal (SIGCONT, cont_handler);
2188   signal (SIGTSTP, tstp_handler);
2191 @group
2192 /* @r{Enable both handlers during program initialization.} */
2195 main (void)
2197   signal (SIGCONT, cont_handler);
2198   signal (SIGTSTP, tstp_handler);
2199   @dots{}
2201 @end group
2202 @end smallexample
2204 @strong{Portability note:} @code{raise} was invented by the ANSI C
2205 committee.  Older systems may not support it, so using @code{kill} may
2206 be more portable.  @xref{Signaling Another Process}.
2208 @node Signaling Another Process
2209 @subsection Signaling Another Process
2211 @cindex killing a process
2212 The @code{kill} function can be used to send a signal to another process.
2213 In spite of its name, it can be used for a lot of things other than
2214 causing a process to terminate.  Some examples of situations where you
2215 might want to send signals between processes are:
2217 @itemize @bullet
2218 @item
2219 A parent process starts a child to perform a task---perhaps having the
2220 child running an infinite loop---and then terminates the child when the
2221 task is no longer needed.
2223 @item
2224 A process executes as part of a group, and needs to terminate or notify
2225 the other processes in the group when an error or other event occurs.
2227 @item
2228 Two processes need to synchronize while working together.
2229 @end itemize
2231 This section assumes that you know a little bit about how processes
2232 work.  For more information on this subject, see @ref{Processes}.
2234 The @code{kill} function is declared in @file{signal.h}.
2235 @pindex signal.h
2237 @comment signal.h
2238 @comment POSIX.1
2239 @deftypefun int kill (pid_t @var{pid}, int @var{signum})
2240 The @code{kill} function sends the signal @var{signum} to the process
2241 or process group specified by @var{pid}.  Besides the signals listed in
2242 @ref{Standard Signals}, @var{signum} can also have a value of zero to
2243 check the validity of the @var{pid}.
2245 The @var{pid} specifies the process or process group to receive the
2246 signal:
2248 @table @code
2249 @item @var{pid} > 0
2250 The process whose identifier is @var{pid}.
2252 @item @var{pid} == 0
2253 All processes in the same process group as the sender.
2255 @item @var{pid} < -1
2256 The process group whose identifier is @minus{}@var{pid}.
2258 @item @var{pid} == -1
2259 If the process is privileged, send the signal to all processes except
2260 for some special system processes.  Otherwise, send the signal to all
2261 processes with the same effective user ID.
2262 @end table
2264 A process can send a signal @var{signum} to itself with a call like
2265 @w{@code{kill (getpid(), @var{signum})}}.  If @code{kill} is used by a
2266 process to send a signal to itself, and the signal is not blocked, then
2267 @code{kill} delivers at least one signal (which might be some other
2268 pending unblocked signal instead of the signal @var{signum}) to that
2269 process before it returns.
2271 The return value from @code{kill} is zero if the signal can be sent
2272 successfully.  Otherwise, no signal is sent, and a value of @code{-1} is
2273 returned.  If @var{pid} specifies sending a signal to several processes,
2274 @code{kill} succeeds if it can send the signal to at least one of them.
2275 There's no way you can tell which of the processes got the signal
2276 or whether all of them did.
2278 The following @code{errno} error conditions are defined for this function:
2280 @table @code
2281 @item EINVAL
2282 The @var{signum} argument is an invalid or unsupported number.
2284 @item EPERM
2285 You do not have the privilege to send a signal to the process or any of
2286 the processes in the process group named by @var{pid}.
2288 @item ESCRH
2289 The @var{pid} argument does not refer to an existing process or group.
2290 @end table
2291 @end deftypefun
2293 @comment signal.h
2294 @comment BSD
2295 @deftypefun int killpg (int @var{pgid}, int @var{signum})
2296 This is similar to @code{kill}, but sends signal @var{signum} to the
2297 process group @var{pgid}.  This function is provided for compatibility
2298 with BSD; using @code{kill} to do this is more portable.
2299 @end deftypefun
2301 As a simple example of @code{kill}, the call @w{@code{kill (getpid (),
2302 @var{sig})}} has the same effect as @w{@code{raise (@var{sig})}}.
2304 @node Permission for kill
2305 @subsection Permission for using @code{kill}
2307 There are restrictions that prevent you from using @code{kill} to send
2308 signals to any random process.  These are intended to prevent antisocial
2309 behavior such as arbitrarily killing off processes belonging to another
2310 user.  In typical use, @code{kill} is used to pass signals between
2311 parent, child, and sibling processes, and in these situations you
2312 normally do have permission to send signals.  The only common execption
2313 is when you run a setuid program in a child process; if the program
2314 changes its real UID as well as its effective UID, you may not have
2315 permission to send a signal.  The @code{su} program does this.
2317 Whether a process has permission to send a signal to another process
2318 is determined by the user IDs of the two processes.  This concept is
2319 discussed in detail in @ref{Process Persona}.
2321 Generally, for a process to be able to send a signal to another process,
2322 either the sending process must belong to a privileged user (like
2323 @samp{root}), or the real or effective user ID of the sending process
2324 must match the real or effective user ID of the receiving process.  If
2325 the receiving process has changed its effective user ID from the
2326 set-user-ID mode bit on its process image file, then the owner of the
2327 process image file is used in place of its current effective user ID.
2328 In some implementations, a parent process might be able to send signals
2329 to a child process even if the user ID's don't match, and other
2330 implementations might enforce other restrictions.
2332 The @code{SIGCONT} signal is a special case.  It can be sent if the
2333 sender is part of the same session as the receiver, regardless of
2334 user IDs.
2336 @node Kill Example
2337 @subsection Using @code{kill} for Communication
2338 @cindex interprocess communication, with signals
2339 Here is a longer example showing how signals can be used for
2340 interprocess communication.  This is what the @code{SIGUSR1} and
2341 @code{SIGUSR2} signals are provided for.  Since these signals are fatal
2342 by default, the process that is supposed to receive them must trap them
2343 through @code{signal} or @code{sigaction}.
2345 In this example, a parent process forks a child process and then waits
2346 for the child to complete its initialization.  The child process tells
2347 the parent when it is ready by sending it a @code{SIGUSR1} signal, using
2348 the @code{kill} function.
2350 @smallexample
2351 @include sigusr.c.texi
2352 @end smallexample
2354 This example uses a busy wait, which is bad, because it wastes CPU
2355 cycles that other programs could otherwise use.  It is better to ask the
2356 system to wait until the signal arrives.  See the example in
2357 @ref{Waiting for a Signal}.
2359 @node Blocking Signals
2360 @section Blocking Signals
2361 @cindex blocking signals
2363 Blocking a signal means telling the operating system to hold it and
2364 deliver it later.  Generally, a program does not block signals
2365 indefinitely---it might as well ignore them by setting their actions to
2366 @code{SIG_IGN}.  But it is useful to block signals briefly, to prevent
2367 them from interrupting sensitive operations.  For instance:
2369 @itemize @bullet
2370 @item
2371 You can use the @code{sigprocmask} function to block signals while you
2372 modify global variables that are also modified by the handlers for these 
2373 signals.
2375 @item
2376 You can set @code{sa_mask} in your @code{sigaction} call to block
2377 certain signals while a particular signal handler runs.  This way, the
2378 signal handler can run without being interrupted itself by signals.
2379 @end itemize
2381 @menu
2382 * Why Block::                           The purpose of blocking signals.
2383 * Signal Sets::                         How to specify which signals to
2384                                          block. 
2385 * Process Signal Mask::                 Blocking delivery of signals to your
2386                                          process during normal execution.
2387 * Testing for Delivery::                Blocking to Test for Delivery of
2388                                          a Signal. 
2389 * Blocking for Handler::                Blocking additional signals while a
2390                                          handler is being run.
2391 * Checking for Pending Signals::        Checking for Pending Signals
2392 * Remembering a Signal::                How you can get almost the same
2393                                          effect as blocking a signal, by
2394                                          handling it and setting a flag
2395                                          to be tested later. 
2396 @end menu
2398 @node Why Block
2399 @subsection Why Blocking Signals is Useful
2401 Temporary blocking of signals with @code{sigprocmask} gives you a way to
2402 prevent interrupts during critical parts of your code.  If signals
2403 arrive in that part of the program, they are delivered later, after you
2404 unblock them.
2406 One example where this is useful is for sharing data between a signal
2407 handler and the rest of the program.  If the type of the data is not
2408 @code{sig_atomic_t} (@pxref{Atomic Data Access}), then the signal
2409 handler could run when the rest of the program has only half finished
2410 reading or writing the data.  This would lead to confusing consequences.
2412 To make the program reliable, you can prevent the signal handler from
2413 running while the rest of the program is examining or modifying that
2414 data---by blocking the appropriate signal around the parts of the
2415 program that touch the data.
2417 Blocking signals is also necessary when you want to perform a certain
2418 action only if a signal has not arrived.  Suppose that the handler for
2419 the signal sets a flag of type @code{sig_atomic_t}; you would like to
2420 test the flag and perform the action if the flag is not set.  This is
2421 unreliable.  Suppose the signal is delivered immediately after you test
2422 the flag, but before the consequent action: then the program will
2423 perform the action even though the signal has arrived.
2425 The only way to test reliably for whether a signal has yet arrived is to
2426 test while the signal is blocked.
2428 @node Signal Sets
2429 @subsection Signal Sets
2431 All of the signal blocking functions use a data structure called a
2432 @dfn{signal set} to specify what signals are affected.  Thus, every
2433 activity involves two stages: creating the signal set, and then passing
2434 it as an argument to a library function.
2435 @cindex signal set
2437 These facilities are declared in the header file @file{signal.h}.
2438 @pindex signal.h
2440 @comment signal.h
2441 @comment POSIX.1
2442 @deftp {Data Type} sigset_t
2443 The @code{sigset_t} data type is used to represent a signal set.
2444 Internally, it may be implemented as either an integer or structure
2445 type.
2447 For portability, use only the functions described in this section to
2448 initialize, change, and retrieve information from @code{sigset_t}
2449 objects---don't try to manipulate them directly.
2450 @end deftp
2452 There are two ways to initialize a signal set.  You can initially
2453 specify it to be empty with @code{sigemptyset} and then add specified
2454 signals individually.  Or you can specify it to be full with
2455 @code{sigfillset} and then delete specified signals individually.
2457 You must always initialize the signal set with one of these two
2458 functions before using it in any other way.  Don't try to set all the
2459 signals explicitly because the @code{sigset_t} object might include some
2460 other information (like a version field) that needs to be initialized as
2461 well.  (In addition, it's not wise to put into your program an
2462 assumption that the system has no signals aside from the ones you know
2463 about.)
2465 @comment signal.h
2466 @comment POSIX.1
2467 @deftypefun int sigemptyset (sigset_t *@var{set})
2468 This function initializes the signal set @var{set} to exclude all of the
2469 defined signals.  It always returns @code{0}.
2470 @end deftypefun
2472 @comment signal.h
2473 @comment POSIX.1
2474 @deftypefun int sigfillset (sigset_t *@var{set})
2475 This function initializes the signal set @var{set} to include
2476 all of the defined signals.  Again, the return value is @code{0}.
2477 @end deftypefun
2479 @comment signal.h
2480 @comment POSIX.1
2481 @deftypefun int sigaddset (sigset_t *@var{set}, int @var{signum})
2482 This function adds the signal @var{signum} to the signal set @var{set}.
2483 All @code{sigaddset} does is modify @var{set}; it does not block or
2484 unblock any signals.
2486 The return value is @code{0} on success and @code{-1} on failure.
2487 The following @code{errno} error condition is defined for this function:
2489 @table @code
2490 @item EINVAL
2491 The @var{signum} argument doesn't specify a valid signal.
2492 @end table
2493 @end deftypefun
2495 @comment signal.h
2496 @comment POSIX.1
2497 @deftypefun int sigdelset (sigset_t *@var{set}, int @var{signum})
2498 This function removes the signal @var{signum} from the signal set
2499 @var{set}.  All @code{sigdelset} does is modify @var{set}; it does not
2500 block or unblock any signals.  The return value and error conditions are
2501 the same as for @code{sigaddset}.
2502 @end deftypefun
2504 Finally, there is a function to test what signals are in a signal set:
2506 @comment signal.h
2507 @comment POSIX.1
2508 @deftypefun int sigismember (const sigset_t *@var{set}, int @var{signum})
2509 The @code{sigismember} function tests whether the signal @var{signum} is
2510 a member of the signal set @var{set}.  It returns @code{1} if the signal
2511 is in the set, @code{0} if not, and @code{-1} if there is an error.
2513 The following @code{errno} error condition is defined for this function:
2515 @table @code
2516 @item EINVAL
2517 The @var{signum} argument doesn't specify a valid signal.
2518 @end table
2519 @end deftypefun
2521 @node Process Signal Mask
2522 @subsection Process Signal Mask
2523 @cindex signal mask
2524 @cindex process signal mask
2526 The collection of signals that are currently blocked is called the
2527 @dfn{signal mask}.  Each process has its own signal mask.  When you
2528 create a new process (@pxref{Creating a Process}), it inherits its
2529 parent's mask.  You can block or unblock signals with total flexibility
2530 by modifying the signal mask.
2532 The prototype for the @code{sigprocmask} function is in @file{signal.h}.
2533 @pindex signal.h
2535 @comment signal.h
2536 @comment POSIX.1
2537 @deftypefun int sigprocmask (int @var{how}, const sigset_t *@var{set}, sigset_t *@var{oldset})
2538 The @code{sigprocmask} function is used to examine or change the calling
2539 process's signal mask.  The @var{how} argument determines how the signal
2540 mask is changed, and must be one of the following values:
2542 @table @code
2543 @comment signal.h
2544 @comment POSIX.1
2545 @vindex SIG_BLOCK
2546 @item SIG_BLOCK
2547 Block the signals in @code{set}---add them to the existing mask.  In
2548 other words, the new mask is the union of the existing mask and
2549 @var{set}.
2551 @comment signal.h
2552 @comment POSIX.1
2553 @vindex SIG_UNBLOCK
2554 @item SIG_UNBLOCK
2555 Unblock the signals in @var{set}---remove them from the existing mask.
2557 @comment signal.h
2558 @comment POSIX.1
2559 @vindex SIG_SETMASK
2560 @item SIG_SETMASK
2561 Use @var{set} for the mask; ignore the previous value of the mask.
2562 @end table
2564 The last argument, @var{oldset}, is used to return information about the
2565 old process signal mask.  If you just want to change the mask without
2566 looking at it, pass a null pointer as the @var{oldset} argument.
2567 Similarly, if you want to know what's in the mask without changing it,
2568 pass a null pointer for @var{set} (in this case the @var{how} argument
2569 is not significant).  The @var{oldset} argument is often used to
2570 remember the previous signal mask in order to restore it later.  (Since
2571 the signal mask is inherited over @code{fork} and @code{exec} calls, you
2572 can't predict what its contents are when your program starts running.)
2574 If invoking @code{sigprocmask} causes any pending signals to be
2575 unblocked, at least one of those signals is delivered to the process
2576 before @code{sigprocmask} returns.  The order in which pending signals
2577 are delivered is not specified, but you can control the order explicitly
2578 by making multiple @code{sigprocmask} calls to unblock various signals
2579 one at a time.
2581 The @code{sigprocmask} function returns @code{0} if successful, and @code{-1}
2582 to indicate an error.  The following @code{errno} error conditions are
2583 defined for this function:
2585 @table @code
2586 @item EINVAL
2587 The @var{how} argument is invalid.
2588 @end table
2590 You can't block the @code{SIGKILL} and @code{SIGSTOP} signals, but
2591 if the signal set includes these, @code{sigprocmask} just ignores
2592 them instead of returning an error status.
2594 Remember, too, that blocking program error signals such as @code{SIGFPE}
2595 leads to undesirable results for signals generated by an actual program
2596 error (as opposed to signals sent with @code{raise} or @code{kill}).
2597 This is because your program may be too broken to be able to continue
2598 executing to a point where the signal is unblocked again.
2599 @xref{Program Error Signals}.
2600 @end deftypefun
2602 @node Testing for Delivery
2603 @subsection Blocking to Test for Delivery of a Signal
2605 Now for a simple example.  Suppose you establish a handler for
2606 @code{SIGALRM} signals that sets a flag whenever a signal arrives, and
2607 your main program checks this flag from time to time and then resets it.
2608 You can prevent additional @code{SIGALRM} signals from arriving in the
2609 meantime by wrapping the critical part of the code with calls to
2610 @code{sigprocmask}, like this:
2612 @smallexample
2613 /* @r{This variable is set by the SIGALRM signal handler.} */
2614 volatile sig_atomic_t flag = 0;
2617 main (void)
2619   sigset_t block_alarm;
2621   @dots{}
2623   /* @r{Initialize the signal mask.} */
2624   sigemptyset (&block_alarm);
2625   sigaddset (&block_alarm, SIGALRM);
2627 @group
2628   while (1)
2629     @{
2630       /* @r{Check if a signal has arrived; if so, reset the flag.} */
2631       sigprocmask (SIG_BLOCK, &block_alarm, NULL);
2632       if (flag)
2633         @{
2634           @var{actions-if-not-arrived}
2635           flag = 0;
2636         @}
2637       sigprocmask (SIG_UNBLOCK, &block_alarm, NULL);
2639       @dots{}
2640     @}
2642 @end group
2643 @end smallexample
2645 @node Blocking for Handler
2646 @subsection Blocking Signals for a Handler
2647 @cindex blocking signals, in a handler
2649 When a signal handler is invoked, you usually want it to be able to
2650 finish without being interrupted by another signal.  From the moment the
2651 handler starts until the moment it finishes, you must block signals that
2652 might confuse it or corrupt its data.
2654 When a handler function is invoked on a signal, that signal is
2655 automatically blocked (in addition to any other signals that are already
2656 in the process's signal mask) during the time the handler is running.
2657 If you set up a handler for @code{SIGTSTP}, for instance, then the
2658 arrival of that signal forces further @code{SIGTSTP} signals to wait
2659 during the execution of the handler.
2661 However, by default, other kinds of signals are not blocked; they can
2662 arrive during handler execution.
2664 The reliable way to block other kinds of signals during the execution of
2665 the handler is to use the @code{sa_mask} member of the @code{sigaction}
2666 structure.
2668 Here is an example:
2670 @smallexample
2671 #include <signal.h>
2672 #include <stddef.h>
2674 void catch_stop ();
2676 void
2677 install_handler (void)
2679   struct sigaction setup_action;
2680   sigset_t block_mask;
2682   sigemptyset (&block_mask);
2683   /* @r{Block other terminal-generated signals while handler runs.} */
2684   sigaddset (&block_mask, SIGINT);
2685   sigaddset (&block_mask, SIGQUIT);
2686   setup_action.sa_handler = catch_stop;
2687   setup_action.sa_mask = block_mask;
2688   setup_action.sa_flags = 0;
2689   sigaction (SIGTSTP, &setup_action, NULL);
2691 @end smallexample
2693 This is more reliable than blocking the other signals explicitly in the
2694 code for the handler.  If you block signals explicity in the handler,
2695 you can't avoid at least a short interval at the beginning of the
2696 handler where they are not yet blocked.
2698 You cannot remove signals from the process's current mask using this
2699 mechanism.  However, you can make calls to @code{sigprocmask} within
2700 your handler to block or unblock signals as you wish.
2702 In any case, when the handler returns, the system restores the mask that
2703 was in place before the handler was entered.  If any signals that become
2704 unblocked by this restoration are pending, the process will receive
2705 those signals immediately, before returning to the code that was
2706 interrupted.
2708 @node Checking for Pending Signals
2709 @subsection Checking for Pending Signals
2710 @cindex pending signals, checking for
2711 @cindex blocked signals, checking for
2712 @cindex checking for pending signals
2714 You can find out which signals are pending at any time by calling
2715 @code{sigpending}.  This function is declared in @file{signal.h}.
2716 @pindex signal.h
2718 @comment signal.h
2719 @comment POSIX.1
2720 @deftypefun int sigpending (sigset_t *@var{set})
2721 The @code{sigpending} function stores information about pending signals
2722 in @var{set}.  If there is a pending signal that is blocked from
2723 delivery, then that signal is a member of the returned set.  (You can
2724 test whether a particular signal is a member of this set using
2725 @code{sigismember}; see @ref{Signal Sets}.)
2727 The return value is @code{0} if successful, and @code{-1} on failure.
2728 @end deftypefun
2730 Testing whether a signal is pending is not often useful.  Testing when
2731 that signal is not blocked is almost certainly bad design.
2733 Here is an example.
2735 @smallexample
2736 #include <signal.h>
2737 #include <stddef.h>
2739 sigset_t base_mask, waiting_mask;
2741 sigemptyset (&base_mask);
2742 sigaddset (&base_mask, SIGINT);
2743 sigaddset (&base_mask, SIGTSTP);
2745 /* @r{Block user interrupts while doing other processing.} */
2746 sigprocmask (SIG_SETMASK, &base_mask, NULL); 
2747 @dots{}
2749 /* @r{After a while, check to see whether any signals are pending.} */
2750 sigpending (&waiting_mask);
2751 if (sigismember (&waiting_mask, SIGINT)) @{
2752   /* @r{User has tried to kill the process.} */
2754 else if (sigismember (&waiting_mask, SIGTSTP)) @{
2755   /* @r{User has tried to stop the process.} */
2757 @end smallexample
2759 Remember that if there is a particular signal pending for your process,
2760 additional signals of that same type that arrive in the meantime might
2761 be discarded.  For example, if a @code{SIGINT} signal is pending when
2762 another @code{SIGINT} signal arrives, your program will probably only
2763 see one of them when you unblock this signal.
2765 @strong{Portability Note:} The @code{sigpending} function is new in
2766 POSIX.1.  Older systems have no equivalent facility.
2768 @node Remembering a Signal
2769 @subsection Remembering a Signal to Act On Later
2771 Instead of blocking a signal using the library facilities, you can get
2772 almost the same results by making the handler set a flag to be tested
2773 later, when you ``unblock''.  Here is an example:
2775 @smallexample
2776 /* @r{If this flag is nonzero, don't handle the signal right away.} */
2777 volatile sig_atomic_t signal_pending;
2779 /* @r{This is nonzero if a signal arrived and was not handled.} */
2780 volatile sig_atomic_t defer_signal;
2782 void
2783 handler (int signum)
2785   if (defer_signal)
2786     signal_pending = signum;
2787   else
2788     @dots{} /* @r{``Really'' handle the signal.} */
2791 @dots{}
2793 void
2794 update_mumble (int frob)
2796   /* @r{Prevent signals from having immediate effect.} */
2797   defer_signal++;
2798   /* @r{Now update @code{mumble}, without worrying about interruption.} */
2799   mumble.a = 1;
2800   mumble.b = hack ();
2801   mumble.c = frob;
2802   /* @r{We have updated @code{mumble}.  Handle any signal that came in.} */
2803   defer_signal--;
2804   if (defer_signal == 0 && signal_pending != 0)
2805     raise (signal_pending);
2807 @end smallexample
2809 Note how the particular signal that arrives is stored in
2810 @code{signal_pending}.  That way, we can handle several types of
2811 inconvenient signals with the same mechanism.
2813 We increment and decrement @code{defer_signal} so that nested critical
2814 sections will work properly; thus, if @code{update_mumble} were called
2815 with @code{signal_pending} already nonzero, signals would be deferred
2816 not only within @code{update_mumble}, but also within the caller.  This
2817 is also why we do not check @code{signal_pending} if @code{defer_signal}
2818 is still nonzero.
2820 The incrementing and decrementing of @code{defer_signal} require more
2821 than one instruction; it is possible for a signal to happen in the
2822 middle.  But that does not cause any problem.  If the signal happens
2823 early enough to see the value from before the increment or decrement,
2824 that is equivalent to a signal which came before the beginning of the
2825 increment or decrement, which is a case that works properly.
2827 It is absolutely vital to decrement @code{defer_signal} before testing
2828 @code{signal_pending}, because this avoids a subtle bug.  If we did
2829 these things in the other order, like this,
2831 @smallexample
2832   if (defer_signal == 1 && signal_pending != 0)
2833     raise (signal_pending);
2834   defer_signal--;
2835 @end smallexample
2837 @noindent
2838 then a signal arriving in between the @code{if} statement and the decrement
2839 would be effetively ``lost'' for an indefinite amount of time.  The
2840 handler would merely set @code{defer_signal}, but the program having
2841 already tested this variable, it would not test the variable again.
2843 @cindex timing error in signal handling
2844 Bugs like these are called @dfn{timing errors}.  They are especially bad
2845 because they happen only rarely and are nearly impossible to reproduce.
2846 You can't expect to find them with a debugger as you would find a
2847 reproducible bug.  So it is worth being especially careful to avoid
2848 them.
2850 (You would not be tempted to write the code in this order, given the use
2851 of @code{defer_signal} as a counter which must be tested along with
2852 @code{signal_pending}.  After all, testing for zero is cleaner than
2853 testing for one.  But if you did not use @code{defer_signal} as a
2854 counter, and gave it values of zero and one only, then either order
2855 might seem equally simple.  This is a further advantage of using a
2856 counter for @code{defer_signal}: it will reduce the chance you will
2857 write the code in the wrong order and create a subtle bug.)
2859 @node Waiting for a Signal
2860 @section Waiting for a Signal
2861 @cindex waiting for a signal
2862 @cindex @code{pause} function
2864 If your program is driven by external events, or uses signals for
2865 synchronization, then when it has nothing to do it should probably wait
2866 until a signal arrives.
2868 @menu
2869 * Using Pause::                 The simple way, using @code{pause}.
2870 * Pause Problems::              Why the simple way is often not very good.
2871 * Sigsuspend::                  Reliably waiting for a specific signal.
2872 @end menu
2874 @node Using Pause
2875 @subsection Using @code{pause}
2877 The simple way to wait until a signal arrives is to call @code{pause}.
2878 Please read about its disadvantages, in the following section, before
2879 you use it.
2881 @comment unistd.h
2882 @comment POSIX.1
2883 @deftypefun int pause ()
2884 The @code{pause} function suspends program execution until a signal
2885 arrives whose action is either to execute a handler function, or to
2886 terminate the process.
2888 If the signal causes a handler function to be executed, then
2889 @code{pause} returns.  This is considered an unsuccessful return (since
2890 ``successful'' behavior would be to suspend the program forever), so the
2891 return value is @code{-1}.  Even if you specify that other primitives
2892 should resume when a system handler returns (@pxref{Interrupted
2893 Primitives}), this has no effect on @code{pause}; it always fails when a
2894 signal is handled.
2896 The following @code{errno} error conditions are defined for this function:
2898 @table @code
2899 @item EINTR
2900 The function was interrupted by delivery of a signal.
2901 @end table
2903 If the signal causes program termination, @code{pause} doesn't return
2904 (obviously).
2906 The @code{pause} function is declared in  @file{unistd.h}.
2907 @end deftypefun
2909 @node Pause Problems
2910 @subsection Problems with @code{pause}
2912 The simplicity of @code{pause} can conceal serious timing errors that
2913 can make a program hang mysteriously.
2915 It is safe to use @code{pause} if the real work of your program is done
2916 by the signal handlers themselves, and the ``main program'' does nothing
2917 but call @code{pause}.  Each time a signal is delivered, the handler
2918 will do the next batch of work that is to be done, and then return, so
2919 that the main loop of the program can call @code{pause} again.
2921 You can't safely use @code{pause} to wait until one more signal arrives,
2922 and then resume real work.  Even if you arrange for the signal handler
2923 to cooperate by setting a flag, you still can't use @code{pause}
2924 reliably.  Here is an example of this problem:
2926 @smallexample
2927 /* @r{@code{usr_interrupt} is set by the signal handler.}  */
2928 if (!usr_interrupt)
2929   pause ();
2931 /* @r{Do work once the signal arrives.}  */
2932 @dots{}
2933 @end smallexample
2935 @noindent
2936 This has a bug: the signal could arrive after the variable
2937 @code{usr_interrupt} is checked, but before the call to @code{pause}.
2938 If no further signals arrive, the process would never wake up again.
2940 You can put an upper limit on the excess waiting by using @code{sleep}
2941 in a loop, instead of using @code{pause}.  (@xref{Sleeping}, for more
2942 about @code{sleep}.)  Here is what this looks like:
2944 @smallexample
2945 /* @r{@code{usr_interrupt} is set by the signal handler.}
2946 while (!usr_interrupt)
2947   sleep (1);
2949 /* @r{Do work once the signal arrives.}  */
2950 @dots{}
2951 @end smallexample
2953 For some purposes, that is good enough.  But with a little more
2954 complexity, you can wait reliably until a particular signal handler is
2955 run, using @code{sigsuspend}.
2956 @ifinfo
2957 @xref{Sigsuspend}.
2958 @end ifinfo
2960 @node Sigsuspend
2961 @subsection Using @code{sigsuspend}
2963 The clean and reliable way to wait for a signal to arrive is to block it
2964 and then use @code{sigsuspend}.  By using @code{sigsuspend} in a loop,
2965 you can wait for certain kinds of signals, while letting other kinds of
2966 signals be handled by their handlers.
2968 @comment signal.h
2969 @comment POSIX.1
2970 @deftypefun int sigsuspend (const sigset_t *@var{set})
2971 This function replaces the process's signal mask with @var{set} and then
2972 suspends the process until a signal is delivered whose action is either
2973 to terminate the process or invoke a signal handling function.  In other
2974 words, the program is effectively suspended until one of the signals that
2975 is not a member of @var{set} arrives.
2977 If the process is woken up by deliver of a signal that invokes a handler
2978 function, and the handler function returns, then @code{sigsuspend} also
2979 returns.
2981 The mask remains @var{set} only as long as @code{sigsuspend} is waiting.
2982 The function @code{sigsuspend} always restores the previous signal mask
2983 when it returns.  
2985 The return value and error conditions are the same as for @code{pause}.
2986 @end deftypefun
2988 With @code{sigsuspend}, you can replace the @code{pause} or @code{sleep}
2989 loop in the previous section with something completely reliable:
2991 @smallexample
2992 sigset_t mask, oldmask;
2994 @dots{}
2996 /* @r{Set up the mask of signals to temporarily block.} */ 
2997 sigemptyset (&mask); 
2998 sigaddset (&mask, SIGUSR1);
3000 @dots{}
3002 /* @r{Wait for a signal to arrive.} */
3003 sigprocmask (SIG_BLOCK, &mask, &oldmask);
3004 while (!usr_interrupt)
3005   sigsuspend (&oldmask);
3006 sigprocmask (SIG_UNBLOCK, &mask, NULL);
3007 @end smallexample
3009 This last piece of code is a little tricky.  The key point to remember
3010 here is that when @code{sigsuspend} returns, it resets the process's
3011 signal mask to the original value, the value from before the call to
3012 @code{sigsuspend}---in this case, the @code{SIGUSR1} signal is once
3013 again blocked.  The second call to @code{sigprocmask} is
3014 necessary to explicitly unblock this signal.
3016 One other point: you may be wondering why the @code{while} loop is
3017 necessary at all, since the program is apparently only waiting for one
3018 @code{SIGUSR1} signal.  The answer is that the mask passed to
3019 @code{sigsuspend} permits the process to be woken up by the delivery of
3020 other kinds of signals, as well---for example, job control signals.  If
3021 the process is woken up by a signal that doesn't set
3022 @code{usr_interrupt}, it just suspends itself again until the ``right''
3023 kind of signal eventually arrives.
3025 This technique takes a few more lines of preparation, but that is needed
3026 just once for each kind of wait criterion you want to use.  The code
3027 that actually waits is just four lines.
3029 @node Signal Stack
3030 @section Using a Separate Signal Stack
3032 A signal stack is a special area of memory to be used as the execution
3033 stack during signal handlers.  It should be fairly large, to avoid any
3034 danger that it will overflow in turn; the macro @code{SIGSTKSZ} is
3035 defined to a canonical size for signal stacks.  You can use
3036 @code{malloc} to allocate the space for the stack.  Then call
3037 @code{sigaltstack} or @code{sigstack} to tell the system to use that
3038 space for the signal stack.
3040 You don't need to write signal handlers differently in order to use a
3041 signal stack.  Switching from one stack to the other happens
3042 automatically.  (Some non-GNU debuggers on some machines may get
3043 confused if you examine a stack trace while a handler that uses the
3044 signal stack is running.)
3046 There are two interfaces for telling the system to use a separate signal
3047 stack.  @code{sigstack} is the older interface, which comes from 4.2
3048 BSD.  @code{sigaltstack} is the newer interface, and comes from 4.4
3049 BSD.  The @code{sigaltstack} interface has the advantage that it does
3050 not require your program to know which direction the stack grows, which
3051 depends on the specific machine and operating system.
3053 @comment signal.h
3054 @comment BSD
3055 @deftp {Data Type} {struct sigaltstack}
3056 This structure describes a signal stack.  It contains the following members:
3058 @table @code
3059 @item void *ss_sp
3060 This points to the base of the signal stack.
3062 @item size_t ss_size
3063 This is the size (in bytes) of the signal stack which @samp{ss_sp} points to.
3064 You should set this to however much space you allocated for the stack.
3066 There are two macros defined in @file{signal.h} that you should use in
3067 calculating this size:
3069 @vtable @code
3070 @item SIGSTKSZ
3071 This is the canonical size for a signal stack.  It is judged to be
3072 sufficient for normal uses.
3074 @item MINSIGSTKSZ
3075 This is the amount of signal stack space the operating system needs just
3076 to implement signal delivery.  The size of a signal stack @strong{must}
3077 be greater than this.
3079 For most cases, just using @code{SIGSTKSZ} for @code{ss_size} is
3080 sufficient.  But if you know how much stack space your program's signal
3081 handlers will need, you may want to use a different size.  In this case,
3082 you should allocate @code{MINSIGSTKSZ} additional bytes for the signal
3083 stack and increase @code{ss_size} accordinly.
3084 @end vtable
3086 @item int ss_flags
3087 This field contains the bitwise @sc{or} of these flags:
3089 @vtable @code
3090 @item SA_DISABLE
3091 This tells the system that it should not use the signal stack.
3093 @item SA_ONSTACK
3094 This is set by the system, and indicates that the signal stack is
3095 currently in use.  If this bit is not set, then signals will be
3096 delivered on the normal user stack.
3097 @end vtable
3098 @end table
3099 @end deftp
3101 @comment signal.h
3102 @comment BSD
3103 @deftypefun int sigaltstack (const struct sigaltstack *@var{stack}, struct sigaltstack *@var{oldstack})
3104 The @code{sigaltstack} function specifies an alternate stack for use
3105 during signal handling.  When a signal is received by the process and
3106 its action indicates that the signal stack is used, the system arranges
3107 a switch to the currently installed signal stack while the handler for
3108 that signal is executed.
3110 If @var{oldstack} is not a null pointer, information about the currently
3111 installed signal stack is returned in the location it points to.  If
3112 @var{stack} is not a null pointer, then this is installed as the new
3113 stack for use by signal handlers.
3115 The return value is @code{0} on success and @code{-1} on failure.  If
3116 @code{sigaltstack} fails, it sets @code{errno} to one of these values:
3118 @table @code
3119 @item
3120 @item EINVAL
3121 You tried to disable a stack that was in fact currently in use.
3123 @item ENOMEM
3124 The size of the alternate stack was too small.  
3125 It must be greater than @code{MINSIGSTKSZ}.
3126 @end table
3127 @end deftypefun
3129 Here is the older @code{sigstack} interface.  You should use
3130 @code{sigaltstack} instead on systems that have it.
3132 @comment signal.h
3133 @comment BSD
3134 @deftp {Data Type} {struct sigstack}
3135 This structure describes a signal stack.  It contains the following members:
3137 @table @code
3138 @item void *ss_sp
3139 This is the stack pointer.  If the stack grows downwards on your
3140 machine, this should point to the top of the area you allocated.  If the
3141 stack grows upwards, it should point to the bottom.
3143 @item int ss_onstack
3144 This field is true if the process is currently using this stack.
3145 @end table
3146 @end deftp
3148 @comment signal.h
3149 @comment BSD
3150 @deftypefun int sigstack (const struct sigstack *@var{stack}, struct sigstack *@var{oldstack})
3151 The @code{sigstack} function specifies an alternate stack for use during
3152 signal handling.  When a signal is received by the process and its
3153 action indicates that the signal stack is used, the system arranges a
3154 switch to the currently installed signal stack while the handler for
3155 that signal is executed.
3157 If @var{oldstack} is not a null pointer, information about the currently
3158 installed signal stack is returned in the location it points to.  If
3159 @var{stack} is not a null pointer, then this is installed as the new
3160 stack for use by signal handlers.
3162 The return value is @code{0} on success and @code{-1} on failure.
3163 @end deftypefun
3165 @node BSD Signal Handling
3166 @section BSD Signal Handling
3168 This section describes alternative signal handling functions derived
3169 from BSD Unix.  These facilities were an advance, in their time; today,
3170 they are mostly obsolete, and supported mainly for compatibility with
3171 BSD Unix.
3173 There are many similarities between the BSD and POSIX signal handling
3174 facilities, because the POSIX facilities were inspired by the BSD
3175 facilities.  Besides having different names for all the functions to
3176 avoid conflicts, the main differences between the two are:
3178 @itemize @bullet
3179 @item
3180 BSD Unix represents signal masks as an @code{int} bit mask, rather than
3181 as a @code{sigset_t} object.
3183 @item
3184 The BSD facilities use a different default for whether an interrupted
3185 primitive should fail or resume.  The POSIX facilities make system
3186 calls fail unless you specify that they should resume.  With the BSD
3187 facility, the default is to make system calls resume unless you say they
3188 should fail.  @xref{Interrupted Primitives}.
3189 @end itemize
3191 The BSD facilities are declared in @file{signal.h}.
3192 @pindex signal.h
3194 @menu
3195 * BSD Handler::                 BSD Function to Establish a Handler.
3196 * Blocking in BSD::             BSD Functions for Blocking Signals. 
3197 @end menu
3199 @node BSD Handler
3200 @subsection BSD Function to Establish a Handler
3202 @comment signal.h
3203 @comment BSD
3204 @deftp {Data Type} {struct sigvec}
3205 This data type is the BSD equivalent of @code{struct sigaction}
3206 (@pxref{Advanced Signal Handling}); it is used to specify signal actions
3207 to the @code{sigvec} function.  It contains the following members:
3209 @table @code
3210 @item sighandler_t sv_handler
3211 This is the handler function.
3213 @item int sv_mask
3214 This is the mask of additional signals to be blocked while the handler
3215 function is being called.
3217 @item int sv_flags
3218 This is a bit mask used to specify various flags which affect the
3219 behavior of the signal.  You can also refer to this field as
3220 @code{sv_onstack}.
3221 @end table
3222 @end deftp
3224 These symbolic constants can be used to provide values for the
3225 @code{sv_flags} field of a @code{sigvec} structure.  This field is a bit
3226 mask value, so you bitwise-OR the flags of interest to you together.
3228 @comment signal.h
3229 @comment BSD
3230 @deftypevr Macro int SV_ONSTACK
3231 If this bit is set in the @code{sv_flags} field of a @code{sigvec}
3232 structure, it means to use the signal stack when delivering the signal.
3233 @end deftypevr
3235 @comment signal.h
3236 @comment BSD
3237 @deftypevr Macro int SV_INTERRUPT
3238 If this bit is set in the @code{sv_flags} field of a @code{sigvec}
3239 structure, it means that system calls interrupted by this kind of signal
3240 should not be restarted if the handler returns; instead, the system
3241 calls should return with a @code{EINTR} error status.  @xref{Interrupted
3242 Primitives}.
3243 @end deftypevr
3245 @comment signal.h
3246 @comment Sun
3247 @deftypevr Macro int SV_RESETHAND
3248 If this bit is set in the @code{sv_flags} field of a @code{sigvec}
3249 structure, it means to reset the action for the signal back to
3250 @code{SIG_DFL} when the signal is received.
3251 @end deftypevr
3253 @comment signal.h
3254 @comment BSD
3255 @deftypefun int sigvec (int @var{signum}, const struct sigvec *@var{action},struct sigvec *@var{old-action})
3256 This function is the equivalent of @code{sigaction} (@pxref{Advanced Signal
3257 Handling}); it installs the action @var{action} for the signal @var{signum},
3258 returning information about the previous action in effect for that signal
3259 in @var{old-action}.
3260 @end deftypefun
3262 @comment signal.h
3263 @comment BSD
3264 @deftypefun int siginterrupt (int @var{signum}, int @var{failflag})
3265 This function specifies which approach to use when certain primitives
3266 are interrupted by handling signal @var{signum}.  If @var{failflag} is
3267 false, signal @var{signum} restarts primitives.  If @var{failflag} is
3268 true, handling @var{signum} causes these primitives to fail with error
3269 code @code{EINTR}.  @xref{Interrupted Primitives}.
3270 @end deftypefun
3272 @node Blocking in BSD
3273 @subsection BSD Functions for Blocking Signals 
3275 @comment signal.h
3276 @comment BSD
3277 @deftypefn Macro int sigmask (int @var{signum})
3278 This macro returns a signal mask that has the bit for signal @var{signum}
3279 set.  You can bitwise-OR the results of several calls to @code{sigmask}
3280 together to specify more than one signal.  For example,
3282 @smallexample
3283 (sigmask (SIGTSTP) | sigmask (SIGSTOP)
3284  | sigmask (SIGTTIN) | sigmask (SIGTTOU))
3285 @end smallexample
3287 @noindent
3288 specifies a mask that includes all the job-control stop signals.
3289 @end deftypefn
3291 @comment signal.h
3292 @comment BSD
3293 @deftypefun int sigblock (int @var{mask})
3294 This function is equivalent to @code{sigprocmask} (@pxref{Process Signal
3295 Mask}) with a @var{how} argument of @code{SIG_BLOCK}: it adds the
3296 signals specified by @var{mask} to the calling process's set of blocked
3297 signals.  The return value is the previous set of blocked signals.
3298 @end deftypefun
3300 @comment signal.h
3301 @comment BSD
3302 @deftypefun int sigsetmask (int @var{mask})
3303 This function equivalent to @code{sigprocmask} (@pxref{Process
3304 Signal Mask}) with a @var{how} argument of @code{SIG_SETMASK}: it sets
3305 the calling process's signal mask to @var{mask}.  The return value is
3306 the previous set of blocked signals.
3307 @end deftypefun
3309 @comment signal.h
3310 @comment BSD
3311 @deftypefun int sigpause (int @var{mask})
3312 This function is the equivalent of @code{sigsuspend} (@pxref{Waiting
3313 for a Signal}):  it sets the calling process's signal mask to @var{mask},
3314 and waits for a signal to arrive.  On return the previous set of blocked
3315 signals is restored.
3316 @end deftypefun