Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Appendix C Chapter 8 Solutions 921


This assumes that the standardI/O streamstdoutis closed when the child calls
exit,not the file descriptorSTDOUT_FILENO.Some versions of the standard
I/O library close the file descriptor associated with standardoutput, which would
cause thewriteto standardoutput to also fail. In this case,dupstandardoutput
to another descriptor,and use this new descriptor for thewrite.
8.2 Consider FigureC.8.

#include "apue.h"

static void f1(void), f2(void);

int
main(void)
{
f1();
f2();
_exit(0);
}

static void
f1(void)
{
pid_t pid;

if ((pid = vfork()) < 0)
err_sys("vfork error");
/* child and parent both return */
}

static void
f2(void)
{
char buf[1000]; /* automatic variables */
int i;

for (i = 0; i < sizeof(buf); i++)
buf[i] = 0;
}

Figure C.8 Incorrect use ofvfork

Whenvforkis called, the parent’s stack pointer points to the stack frame for the
f1function that callsvfork.FigureC.9 shows this. vforkcauses the child to
execute first, and the child returns fromf1.The child then callsf2,and its stack
frame overwrites the previous stack frame forf1.The child then zeros out the
automatic variablebuf,setting 1,000 bytes of the stack frame to 0. The child
returns fromf2and then calls_exit,but the contents of the stack beneath the
stack frame formainhave been changed. The parent then resumes after the call
Free download pdf