Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

254 Process Control Chapter 8


Example


The program in Figure8.16 demonstrates theexecfunctions.

#include "apue.h"
#include <sys/wait.h>

char *env_init[]={"USER=unknown", "PATH=/tmp", NULL };

int
main(void)
{
pid_t pid;

if ((pid = fork()) < 0) {
err_sys("fork error");
}else if (pid == 0) { /* specify pathname, specify environment */
if (execle("/home/sar/bin/echoall", "echoall", "myarg1",
"MY ARG2", (char *)0, env_init) < 0)
err_sys("execle error");
}

if (waitpid(pid, NULL, 0) < 0)
err_sys("wait error");

if ((pid = fork()) < 0) {
err_sys("fork error");
}else if (pid == 0) { /* specify filename, inherit environment */
if (execlp("echoall", "echoall", "only 1 arg", (char *)0) < 0)
err_sys("execlp error");
}

exit(0);
}

Figure 8.16Example ofexecfunctions

We first callexecle,which requires a pathname and a specific environment. The
next call is toexeclp,which uses a filename and passes the caller’s environment to the
new program. The only reason the call to execlp works is that the directory
/home/sar/binis one of the current path prefixes. Note also that we set the first
argument,argv[0] in the new program, to be the filename component of the
pathname. Some shells set this argument to be the complete pathname. This is a
convention only; we can setargv[0]to any string we like. Thelogincommand does
this when it executes the shell. Beforeexecuting the shell,loginadds a dash as a prefix
toargv[0]to indicate to the shell that it is being invoked as a login shell.Alogin shell
will execute the start-up profile commands, whereas a nonlogin shell will not.
The programechoallthat is executed twice in the program in Figure8.16 is
shown in Figure8.17. It is a trivial program that echoes all its command-line arguments
and its entireenvironment list.
Free download pdf