Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 8.4 vforkFunction 235


#include "apue.h"
int globvar=6;/*external variable in initialized data */
int
main(void)
{
int var; /* automatic variable on the stack */
pid_t pid;
var = 88;
printf("before vfork\n"); /* we don’t flush stdio */
if ((pid = vfork()) < 0) {
err_sys("vfork error");
}else if (pid == 0) { /* child */
globvar++; /* modify parent’s variables */
var++;
_exit(0); /* child terminates */
}
/* parent continues here */
printf("pid = %ld, glob = %d, var = %d\n", (long)getpid(), globvar,
var);
exit(0);
}

Figure 8.3Example ofvforkfunction

Running this program gives us
$./a.out
before vfork
pid = 29039, glob = 7, var = 89
Here, the incrementing of the variables done by the child changes the values in the
parent. Because the child runs in the address space of the parent, this doesn’t surprise
us. This behavior,however,differs from the behavior offork.
Note in Figure8.3 that we call _exitinstead of exit.As we described in
Section 7.3,_exitdoes not perform any flushing of standardI/O buffers. If we call
exitinstead, the results areindeterminate. Depending on the implementation of the
standardI/O library, we might see no difference in the output, or we might find that the
output from the firstprintfin the parent has disappeared.
If the child callsexit,the implementation flushes the standardI/O streams. If this
is the only action taken by the library,then we will see no difference from the output
generated if the child called_exit.Ifthe implementation also closes the standardI/O
streams, however,the memory representing theFILEobject for the standardoutput
will be cleared out. Because the child is borrowing the parent’s address space, when the
parent resumes and callsprintf, no output will appear andprintfwill return−1.
Note that the parent’sSTDOUT_FILENOis still valid, as the child gets a copy of the
parent’s file descriptor array (refer back to Figure8.2).
Free download pdf