从标准输入读命令并执行
<span style="font-size:14px;">#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<string.h>
#define MAXSIZE 4096
int main()
{
char buf[MAXSIZE];
pid_t pid;
int status;
printf("%% ");
while(fgets(buf,MAXSIZE,stdin) != NULL)
{
if(buf[strlen(buf) - 1] == '\n')
buf[strlen(buf)-1] = 0;
if((pid = fork() ) < 0)
{
printf("fork error\n");
exit(1);
}
else if(pid == 0)
{
execlp(buf,buf,(char*)0);
printf("couldn't execute: %s\n",buf);
exit(127);
}
if((pid = waitpid(pid,&status,0)) < 0)
{
printf("waitpid error\n");
exit(1);
}
printf("%% ");
}
exit(0);
}</span>
1. 标准 I/O函数fgets用于从终端读入一行数据
2. 由于execlp函数要求参数以null结尾,所以用strlen函数求出buf长度用于替换\n为null
3. fork函数用于创建一个新的进程。fork函数向父进程返回新子进程的进程ID,对子进程则返回0。fork被调用一次但返回两次
4. execlp用于执行读入的命令。
5. waitpid函数返回子进程的终止状态(status变量)