signal.texi 133 KB

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