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