资源描述:
《Linux下用C函数实现简单的交互式shell.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、.专业整理.#include
#include
#include
#include
#include
#include
#include
#include
#include
#defineBUF_LEN1024
#defineMAX_FILE_NAME256
#defineMAX_PROCESS_NUM2
#defineMAX_ARGC10
#defineBOOLint
#defineTRUE1
2、
#defineFALSE0
#defineDELIM"
3、<>"
enum
{
E_OPEN=0,
E_PIPE,
E_DUP2,
E_EXECVP,
E_FORK
};
.学习帮手..专业整理.
enum
{
FIRST=0,
SECOND
};
BOOLget_std_file(char*pos_std,char**std_file)
{
if(!pos_std)
returnFALSE;
*pos_std=' ';
*std_file=strtok(pos_std+1,DELIM);
if(*std_file)
returnTRUE;
returnFALSE;
}
BOO
4、Lget_cmd_args(char*str,char**args)
{
inti=0;
if(!str)
returnFALSE;
if(!(args[i++]=strtok(str,DELIM)))
returnFALSE;
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;
ch
5、ar*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));
buf[0]=' ';
6、
bzero(first,sizeof(first));
bzero(second,sizeof(second));
if(!(fgets(buf,BUF_LEN,stdin)))
break;
if(buf[0]==''
7、
8、buf[0]==' ')
continue;
pos=strchr(buf,'');
if(pos)
*pos=' ';
if(0==strcmp(buf,"exit"))
break;
pos_pipe=strchr(buf,'
9、');
pos_stdin=strchr(buf,'<');
pos_stdout=strchr(buf,'>');
i
10、f(pos_pipe)
*pos_pipe='
11、';
.学习帮手..专业整理.if(pos_stdin)
if(!get_std_file(pos_stdin,&stdin_file))
continue;
if(pos_stdout)
if(!get_std_file(pos_stdout,&stdout_file))
continue;
if(!get_cmd_args(buf,first))
continue;
if(pos_pipe)
if(!get_cmd_args(pos_pipe+1,second))
continue;
if(!pos_pipe)
{
pid=fork(
12、);
if(0==pid)
{
if(pos_stdin)
{
fd=open(stdin_file,O_RDONLY);
if(fd<0)
{
perror("openfail");
exit(E_OPEN);
}
dup2(fd,STDIN_FILENO);
}
if(pos_stdout)
.学习帮手..专业整理.{
fd=open(stdout_file,O_WRONLY
13、O_CREAT
14、O_TRUNC,0644);
if(fd<0