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