Interpreter Files

所谓的Interpreter File就是文件的首行为

#! pathname [optional-argument]

的文件。

 

The recognition of these files is done within the kernel as part of processing the exec system call.

这个是由kernel,在exec时认出该类文件并执行的。

 

pathname指出的就是Interpreter ,实际kernel会运行pathname指定的程序。

 

来看一下这个东东运行的情况。

 

首先 建立一个程序echoall ,用来输出所有的参数。

 

/*
 * =====================================================================================
 *
 *       Filename:  echoall.c
  * =====================================================================================
 */

#include <stdio.h>

int main(int argc, char* argv[])
{
    int i;

    for (i=0; i<argc; i++)
    {
        printf("argc[%d]: %s/n", i, argv[i]);
    }
    fflush(stdout);
}


然后 写个Interpreter File,来调用echoall

#!/home/wyang/test/echoall test
这个文件中,就只有一行。就是用来调用echoall程序的。

而test就是传给echoall的参数。

 

好了,再写一个程序通过exec 来调用echoall

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

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

int main(void)
{
    pid_t  pid;

    if ((pid = fork()) < 0)
    {
        perror("fork error");
        return 0;
    }
    else if (pid == 0)
    {
        if (execlp("bash.sh", "echoall", "only 1 arg", (char*)0) < 0)
        {
            perror("execlp error");
            return 0;
        }
    }


    return 0;
}

 

这个程序就是用exec运行了bash.sh这个interpreter file。 然后我们看运行的结果。

argc[0]: /home/wyang/test/echoall
argc[1]: test
argc[2]: ./bash.sh
argc[3]: only 1 arg

 

说明

1. 实际运行的是echoall这个程序,而不是bash.sh本生。

    也就是执行的是Interpreter ,而不是Interpreter File

2. 参数test紧跟在arg[0]后面。

3. exec传入的参数bash.sh, echoall中,只有第一个文件名参数(bash.sh),传给了echoall。

    而第二个参数"echoall",被丢弃了。

4. exec接下来的参数,"only 1 arg",也传给了echoall。

 

 

=====================

最后,可以直接在bash中运行该文件

$./bash.sh
argc[0]: /home/wyang/test/echoall
argc[1]: test
argc[2]: ./bash.sh

 

结果也是一样的。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值