资源描述:
《Linux下用C函数实现简单的交互式shell》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、#include
#include
#include
#include
#include
#include
#include
#include
#include
#defineBUF_LEN1024
#defineMAX_FILE_NAME256
#defineMAX_PROCESS_NUM2
#defineMAX_ARG
2、C10
#defineBOOLint
#defineTRUE1
#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
4、+1,DELIM);
if(*std_file)
returnTRUE;
returnFALSE;
}
BOOLget_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[])
{
cha
5、rbuf[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=
6、NULL;
pos_pipe=NULL;
buf[0]=' ';
printf("akaedu@caihui-desktop:%s#",getcwd(buf,BUF_LEN));
buf[0]=' ';
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(bu
9、f,'');
if(pos)
*pos=' ';
if(0==strcmp(buf,"exit"))
break;
pos_pipe=strchr(buf,'
10、');
pos_stdin=strchr(buf,'<');
pos_stdout=strchr(buf,'>');
if(pos_pipe)
*pos_pipe='
11、';
if(pos_stdin)
if(!get_std_file(pos_stdin,&stdin_file))
continue;
if(pos_stdout)
if(!get_s
12、td_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();
if(0==pid)
{
if(pos_stdin)
{
fd=open(stdin_file,O_RDONLY);
if(fd<0)
{
perror("openfail
13、");
exit(E_OPEN);
}
dup2(fd,STDIN_FILENO);
}
if(pos_stdout)
{
fd=open(stdout_file,O_WRONLY
14、O_CREAT
15、O_TRUNC,0644);
if(fd<0)
{
perror("openfail");
exit(E_OPEN);
}
dup2(fd,STDOUT_FILENO);