Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 8.10 execFunctions 249


In the program shown in Figure8.13, the parent goes first. The child goes first if we
change the lines following theforkto be
}else if (pid == 0) {
charatatime("output from child\n");
TELL_PARENT(getppid());
}else {
WAIT_CHILD(); /* child goes first */
charatatime("output from parent\n");
}
Exercise 8.4 continues this example.

8.10 execFunctions


We mentioned in Section 8.3 that one use of theforkfunction is to create a new process
(the child) that then causes another program to be executed by calling one of theexec
functions. Whenaprocess calls one of theexecfunctions, that process is completely
replaced by the new program, and the new program starts executing at itsmain
function. The process ID does not change across anexec,because a new process is not
created;execmerely replaces the current process — its text, data, heap, and stack
segments — withabrand-new program from disk.
Thereare seven differentexecfunctions, but we’ll often simply refer to ‘‘theexec
function,’’which means that we could use any of the seven functions. These seven
functions round out the UNIX System process control primitives. Withfork, we can
create new processes; and with theexecfunctions, we can initiate new programs. The
exitfunction and thewaitfunctions handle termination and waiting for termination.
These arethe only process control primitives we need. We’ll use these primitives in
later sections to build additional functions, such aspopenandsystem.

#include <unistd.h>

int execl(const char *pathname,const char *arg0,... /* (char *)0 */ );

int execv(const char *pathname,char *constargv[]);

int execle(const char *pathname,const char *arg0,...
/* (char *)0, char *constenvp[] */ );

int execve(const char *pathname,char *const argv[], char *constenvp[]);

int execlp(const char *filename,const char *arg0,... /* (char *)0 */ );

int execvp(const char *filename,char *constargv[]);

int fexecve(int fd,char *constargv[], char *constenvp[]);

All seven return:−1 on error, no return on success
Free download pdf