|
楼主 |
发表于 2003-3-2 23:18:44
|
显示全部楼层
本程序功能的另一个实现的版本,却可以得出正确结果
/* MyShell! v1.0 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <ctype.h>
#include <dirent.h>
#include "mos.h"
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#ifndef TIOCGWINSZ
#include <sys/ioctl.h>
#endif
void PrintTag();
void CallOutsideCommand( );
/* main() */
int main( void )
{
printf( "\t\t\tMyShell! v1.0\n" );
CallOutsideCommand( );//ÍⲿÃüÁî
return 0;
}
/* Show the tag if a new line '\n' was met. */
void PrintTag()
{
//char Buf[MAXPATH]={0X00};
//char* path =getcwd(Buf,MAXPATH);
printf("\n%s","]@" );
}
void CallOutsideCommand( )
{
pid_t pid[3];
int fd[2];
int fds[2];
char *param[4]={0x00};
char *p_cmd;
if((pid[0]=fork())<0)
{
fprintf(stderr,"fork error\n");
return;
}
if(pid[0]==0)//in child1
{
if(pipe(fd)<0)
{
fprintf(stderr,"pipe error\n");
return;
}
if(pid[1]=fork()==0)
{
if(pipe(fds)<0)
{
fprintf(stderr,"pipe error\n");
return;
}
if(pid[2]=fork()==0)
{
close(fds[0]);//¹Ø±Õ¶Á¶Ë
if(fds[1]!=STDOUT_FILENO)
{
if(dup2(fds[1],STDOUT_FILENO)!=STDOUT_FILENO)
{
fprintf(stderr,"dup2 error to stdin\n");
return;
}
close(fds[1]);
}
p_cmd="ls";
param[0]="ls";
param[1]="-l";
param[2]=NULL;
if(execvp(p_cmd,param)<0)
{
fprintf(stderr,"execvp error for ls\n");
PrintTag();
return;
}
}
close(fds[1]);
if(fds[0]!=STDIN_FILENO)
{
if(dup2(fds[0],STDIN_FILENO)!=STDIN_FILENO)
{
fprintf(stderr,"dup2 error to stdin\n");
return;
}
close(fds[0]);
}
close(fd[0]);
if(fd[1]!=STDOUT_FILENO)
{
if(dup2(fd[1],STDOUT_FILENO)!=STDOUT_FILENO)
{
fprintf(stderr,"dup2 error to stdout2\n");
return;
}
close(fd[1]);
}
p_cmd="grep";
param[0]="grep";
param[1]="mos.c";
param[2]=NULL;
if(execvp(p_cmd,param)<0)
{
fprintf(stderr,"execvp error for grep\n");
return;
}
}
close(fd[1]);//¹Ø±Õ¶ÔÉÏÒ»¹ÜµÀµÄд¶Ë
if(fd[0]!=STDIN_FILENO)
{
if(dup2(fd[0],STDIN_FILENO)!=STDIN_FILENO)
{
fprintf(stderr,"dup2 error to stdout3\n");
return;
}
close(fd[0]);
}
p_cmd="wc";
param[0]="wc";
param[1]="-l";
param[2]=NULL;
if(execvp(p_cmd,param)<0)
{
fprintf(stderr,"execl error for wc\n");
PrintTag();
return;
}
}
wait();
return ;
} |
|