Linux下用C函数实现简单的交互式shellWord格式.docx
《Linux下用C函数实现简单的交互式shellWord格式.docx》由会员分享,可在线阅读,更多相关《Linux下用C函数实现简单的交互式shellWord格式.docx(8页珍藏版)》请在冰豆网上搜索。
#defineDELIM"
|<
>
"
enum
{
E_OPEN=0,
E_PIPE,
E_DUP2,
E_EXECVP,
E_FORK
};
FIRST=0,
SECOND
BOOLget_std_file(char*pos_std,char**std_file)
if(!
pos_std)
returnFALSE;
*pos_std='
\0'
;
*std_file=strtok(pos_std+1,DELIM);
if(*std_file)
returnTRUE;
returnFALSE;
}
BOOLget_cmd_args(char*str,char**args)
inti=0;
str)
(args[i++]=strtok(str,DELIM)))
while((args[i++]=strtok(NULL,DELIM)));
returnTRUE;
intmain(intargc,char*argv[])
charbuf[BUF_LEN];
char*first[MAX_ARGC];
char*second[MAX_ARGC];
char*stdin_file;
char*stdout_file;
char*pos;
char*pos_stdin;
char*pos_stdout;
char*pos_pipe;
inti;
intpfd[2];
intfd;
pid_tpids[MAX_PROCESS_NUM];
pid_tpid;
while
(1)
{
pos_stdin=NULL;
pos_stdout=NULL;
pos_pipe=NULL;
buf[0]='
printf("
akaedu@caihui-desktop:
%s#"
getcwd(buf,BUF_LEN));
bzero(first,sizeof(first));
bzero(second,sizeof(second));
if(!
(fgets(buf,BUF_LEN,stdin)))
break;
if(buf[0]=='
\n'
||buf[0]=='
)
continue;
pos=strchr(buf,'
);
if(pos)
*pos='
if(0==strcmp(buf,"
exit"
))
pos_pipe=strchr(buf,'
|'
pos_stdin=strchr(buf,'
<
'
pos_stdout=strchr(buf,'
if(pos_pipe)
*pos_pipe='
if(pos_stdin)
if(!
get_std_file(pos_stdin,&
stdin_file))
continue;
if(pos_stdout)
get_std_file(pos_stdout,&
stdout_file))
get_cmd_args(buf,first))
get_cmd_args(pos_pipe+1,second))
pos_pipe)
{
pid=fork();
if(0==pid)
{
if(pos_stdin)
{
fd=open(stdin_file,O_RDONLY);
if(fd<
0)
{
perror("
openfail\n"
exit(E_OPEN);
}
dup2(fd,STDIN_FILENO);
}
if(pos_stdout)
fd=open(stdout_file,O_WRONLY|O_CREAT|O_TRUNC,0644);
dup2(fd,STDOUT_FILENO);
execvp(first[0],first);
perror("
execvpfail\n"
exit(E_EXECVP);
}
else
wait(NULL);
}
else
if(pipe(pfd)<
pipefail\n"
exit(E_PIPE);
pid=getpid();
for(i=0;
i<
MAX_PROCESS_NUM&
&
pid>
0;
i++)
pid=fork();
if(pid<
perror("
forkfail\n"
exit(E_FORK);
elseif(0==pid)
bzero(pids,sizeof(pids));
pids[i]=getpid();
break;
else
pids[i]=pid;
if(pid>
close(pfd[0]);
close(pfd[1]);
MAX_PROCESS_NUM;
if(pids[i]==getpid())
switch(i)
caseFIRST:
close(pfd[0]);
if(pos_stdin)
{
fd=open(stdin_file,O_RDONLY);
if(fd<
{
perror("
exit(E_OPEN);
}
dup2(fd,STDIN_FILENO);
execvp(first[0],first);
perror("
exit(E_EXECVP);
}
break;
caseSECOND:
close(pfd[1]);
if(pos_stdout)
fd=open(stdout_file,O_WRONLY|O_CREAT|O_TRUNC,0644);
dup2(fd,STDOUT_FILENO);
execvp(second[0],second);
}
if(pid>
for(i=0;
wait(NULL);
return0;