这个程序主要根据APUE里面的例子进行修改优化,增加了参数的读取执行功能。
/**********************************************************
Program:
Read commands form stdin and excute them.
History:
2013/04/08 dingdong First release
2013/04/09 dingdong Second release [not finish]
2013/04/30 dingdong Third release [finish]
***********************************************************/
#include"apue.h"
#include<stdio.h>
#include<sys/wait.h>
int
main(int agrc,char *agrv[])
{
char buf[MAXLINE],parameter[MAXLINE];//MAXLINE==4096
pid_t pid;
int status,i=0,j=0,pos;//child status
int flag;
printf("dingdong%% ");//print %% to print %
while(fgets(buf,MAXLINE,stdin)!=NULL)
{
//check the parameter of command
flag=0;
for(i=0;i<strlen(buf);i++)
{
if(buf[i]=='-')//read parameter
{
flag=1;//have parameter
pos=i;//recode positon
while(buf[i]!='\n')
{
parameter[j]=buf[i];
j++;
i++;
}
}
}
i=0;
j=0;
/*replace by NULL*/
parameter[strlen(parameter)]=0;
if(flag)
buf[pos-1]=0;
else
buf[strlen(buf)-1]=0;
//make process
if((pid=fork())<0)
err_sys("fork error!");
//child
else if (pid==0)
{
if(flag)
execlp(buf,buf,parameter,(char *)0);//execute
else
execlp(buf,buf,(char *)0);
err_ret("couldn't execute: %s",buf);
exit(127);
}
//praent
if((pid=waitpid(pid,&status,0))<0)//wait for child
err_sys("waitpid error!");
printf("dingdong%% ");
}
exit(0);
}