Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 10.18 systemFunction 367


We first see whether the default action will occur; if so, we flush all the standardI/O
streams. This is not equivalent to callingfcloseon all the open streams (since it just
flushes them and doesn’t close them), but when the process terminates, the system
closes all open files. If the process catches the signal and returns, we flush all the
streams again, since the process could have generated moreoutput. The only condition
we don’t handle is the case wherethe process catches the signal and calls_exitor
_Exit.Inthis case, any unflushed standardI/O buffers in memory arediscarded. We
assume that a caller that does this doesn’t want the buffers flushed.
Recall from Section 10.9 that if callingkillcauses the signal to be generated for the
caller,and if the signal is not blocked (which we guarantee in Figure10.25), then the
signal (or some other pending, unlocked signal) is delivered to the process beforekill
returns. Weblock all signals exceptSIGABRT, so we know that if the call tokill
returns, the process caught the signal and the signal handler returned.

10.18 systemFunction


In Section 8.13, we showed an implementation of thesystemfunction. That version,
however,did not do any signal handling. POSIX.1 requires thatsystemignoreSIGINT
andSIGQUITand blockSIGCHLD.Beforeshowing a version that handles these signals
correctly,let’s see why we need to worry about signal handling.

Example


The program shown in Figure10.26 uses the version ofsystemfrom Section 8.13 to
invoke theed( 1 )editor.(This editor has been part of UNIX systems for a long time.We
use it herebecause it is an interactive program that catches the interrupt and quit
signals. If we invokeedfrom a shell and type the interrupt character, it catches the
interrupt signal and prints a question mark. Theedprogram also sets the disposition of
the quit signal so that it is ignored.) The program in Figure10.26 catches bothSIGINT
andSIGCHLD.If we invoke the program, we get
$./a.out
a append text to the editor’s buffer
Here is one line of text

. period on a line by itself stops append mode
1,$p print first through last lines of buffer to see what’sthere
Here is one line of text
wtemp.foo write the buffer to a file
25 editor says it wrote 25 bytes
q and leave the editor
caught SIGCHLD
When the editor terminates, the system sends theSIGCHLDsignal to the parent (the
a.outprocess). Wecatch it and return from the signal handler.But if it is catching the
SIGCHLDsignal, the parent should be doing so because it has created its own children,
so that it knows when its children have terminated. The delivery of this signal in the

Free download pdf