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