See the routine 8.10 (exec2.c) First
#include "apue.h" #include <sys/wait.h>
int main (void) { pid_t pid; if ((PID = fork ()) < 0) { Err_sys ("fork Error"); } else if (PID = = 0) {/* Child */ if (Execl ("/home/yao/work/myapue/ch08/testinterp", "Testinterp", "Myarg1", "MY ARG2", (char *) 0) < 0) { Err_sys ("Execl error"); } } if (Waitpid (PID, NULL, 0) < 0)/*/parent */ {
Err_sys ("Waitpid error"); }
Exit (0); } |
Compiling routines
$ gcc–o exec2 exec2.c
Enter the following in the Testinterp file
$ cat > Testinterp
#! /home/yao/work/myapue/ch08/echoarg Foo
EOF (Ctrl+d)
$chmod u+x Testinterp
The contents of the Echoarg.c file are as follows:
#include "apue.h"
Int Main (int argc, char *argv[]) { int i;
for (i = 0; i < argc; i++)/* echo all command-line args */ printf ("argv[%d]:%s/n", I, argv[i]); Exit (0); }
|
Compiling routines Echoarg.c
$ gcc–o Echoarg echoarg.c
Last run./exec2
$./exec2
Argv[0]:/home/yao/work/myapue/ch08/echoarg
ARGV[1]: foo
ARGV[2]:/home/yao/work/myapue/ch08/testinterp
ARGV[3]: Myarg1
ARGV[4]: MY ARG2
This has been better understood so far. It is interesting that the third parameter "./testinterp" appears when you run the Testinterp file.
$./testinterp
Agv[0]:/home/yao/work/myapue/ch08/echoarg
ARGV[1]: foo
ARGV[2]:./testinterp
Because when the shell handles the script file, it calls the fork, exec, and wait functions (the shell of the 06 is how to execute the script), and the program exec2.c the EXECL function with D, first, the EXECL function parses the #! line and concludes that the interpreter for this script is "/ Home/yao/work/myapue/ch08/echoarg ", then formed the command line to be processed into:"/home/yao/work/myapue/ch08/echoarg foo./testinterp ".