手记07之解释器文件(Interpreter Files)

先看例程8.10(exec2.c)

#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);
}

编译例程

$ gcc –o exec2 exec2.c

testinterp文件中输入如下内容

$ cat > testinterp
#! /home/yao/work/myAPUE/ch08/echoarg foo
EOF(Ctrl+D)
$chmod u+x testinterp

echoarg.c的文件内容如下:

#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);
}


编译例程echoarg.c

$ gcc –o echoarg echoarg.c

最后运行./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

这个到目前为止都比较好理解。比较有意思的是当你运行testinterp文件时候出现的第三个参数”./testinterp”

$ ./testinterp
agv[0]: /home/yao/work/myAPUE/ch08/echoarg
argv[1]: foo
argv[2]: ./testinterp

因为在Shell处理脚本文件时,会调用forkexecwait函数(手记06之shell如何执行脚本),和程序exec2.c一样用d调用了execl函数,首先,execl函数对#!行分析后得出此脚本的解释器为”/home/yao/work/myAPUE/ch08/echoarg”,然后就形成了把命令行处理成了:”/home/yao/work/myAPUE/ch08/echoarg foo ./testinterp”

你可能感兴趣的:(APUE(Advanced,Programming,In,The,Unix,Environment)