实例最好用
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAXLEN 4096
int main(void)
{
char buf[MAXLEN];
pid_t pid;
int status;
printf("%%");
while(fgets(buf,MAXLEN,stdin) != NULL) {
if(buf[buf(strlen(buf)-1)] == '\n') {
buf[strlen(buf)-1] = 0;
}
if(pid = fork() < 0) {
err_sys("fork error");
}else if(pid == 0) {
execlp(buf,buf,(char*)0);
err_ret("couldn't execute: %s",buf);
exit(127);
}
if(pid = waitpid(pid,&status,0) < 0) {
err_sys("waitpid error");
}
printf("%%");
}
exit(0);
}
执行结果示例:
$ ./a.out
% date
2019年 03月 10日 星期日 09:16:01 CST
% who
cb :0 2019-03-02 22:14 (:0)
% pwd
/home/cb/Unix/1_part
% ^D 键入文件结束符
$
顺便学习一下execlp的用法
execlp
从PATH 环境变量中查找文件并执行
定义:
int execlp(const char * file,const char * arg,……);
头文件:
#include<unistd.h>
说明:
execlp()会从PATH 环境变量所指的目录中查找符合参数file的文件名, 找到后便执行该文件, 然后将第二个以后的参数当做该文件的argv[0]、argv[1]……, 最后一个参数必须用空指针(NULL)作结束。
返回值:
如果执行成功则函数不会返回, 执行失败则直接返回-1, 失败原因存于errno 中。