The Linux Programming Interface

(nextflipdebug5) #1
Program Execution 589

27.9 Exercises


27-1. The final command in the following shell session uses the program in Listing 27-3
to exec the program xyz. What happens?

$ echo $PATH
/usr/local/bin:/usr/bin:/bin:./dir1:./dir2
$ ls -l dir1
total 8
-rw-r--r-- 1 mtk users 7860 Jun 13 11:55 xyz
$ ls -l dir2
total 28
-rwxr-xr-x 1 mtk users 27452 Jun 13 11:55 xyz
$ ./t_execlp xyz

27-2. Use execve() to implement execlp(). You will need to use the stdarg(3) API to handle
the variable-length argument list supplied to execlp(). You will also need to use
functions in the malloc package to allocate space for the argument and environment
vectors. Finally, note that an easy way of checking whether a file exists in a particular
directory and is executable is simply to try execing the file.
27-3. What output would we see if we make the following script executable and exec() it?

#!/bin/cat -n
Hello world

27-4. What is the effect of the following code? In what circumstances might it be useful?

childPid = fork();
if (childPid == -1)
errExit("fork1");
if (childPid == 0) { /* Child */
switch (fork()) {
case -1: errExit("fork2");

case 0: /* Grandchild */
/* ----- Do real work here ----- */
exit(EXIT_SUCCESS); /* After doing real work */

default:
exit(EXIT_SUCCESS); /* Make grandchild an orphan */
}
}

/* Parent falls through to here */

if (waitpid(childPid, &status, 0) == -1)
errExit("waitpid");

/* Parent carries on to do other things */
Free download pdf