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