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