signal.texi 129 KB

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