《UNIX环境高级编程》笔记--解释器文件

所有的UNIX系统都支持解释器文件,这种文件是文本文件,其起始行的形式是:

#! pathname [ optional-argument ]

常见的解释器文件以下列行开始:

#! /bin/sh

pathname通常是绝对路径名,对它不进行什么特殊的处理。内核调用exec函数的进程实际执行的并不是该解释器文件,

而是该解释器文件的第一行中pathname所指定的文件。一定要将解释器文件(文本文件,它以#!开头)和解释器(由该

解释器文件第一行中的pathname指定区分开来)

下面调用exec执行一个解释器文件。

ptarg:

#include <stdio.h>
int main(int argc, char* argv[]){int i;for(i=0; i<argc; i++){printf("%s ",argv[i]);}printf("\n");return 0;
}

exec:

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>int main(void){pid_t pid;if((pid=fork())<0){perror("fork");return -1;}else if(pid == 0){if(execl("/home/yan/apue/ptargshell","ptargshell","myarg1","myarg2",(char*)0)<0){perror("execl");return -1;}}if(waitpid(pid,NULL,0)<0){perror("waitpid");return -1;}return 0;
}

ptargshell:

#!/home/yan/apue/ptarg foo

执行结果:

yan@yan-vm:~/apue$ ./exec
/home/yan/apue/ptarg foo /home/yan/apue/ptargshell myarg1 myarg2