【问题标题】:Piping in a basic shell implementation在基本的 shell 实现中进行管道化
【发布时间】:2012-11-16 13:09:21
【问题描述】:

在一项任务中,我们被要求实现管道。我可以这样做,但是我遇到的问题是当我输入命令时

ls | grep 'a.out'

那么输出是

a.out

a.out

但是当我这样做时

ls |厕所

输出只出现一次。谁能指出代码中的错误?代码如下:

void execute_pipe(char **argv,char **args)
{

int pfds[2];
pid_t pid,pid2;
int status,status2;
pipe(pfds);
if ((pid = fork()) < 0) {    
      printf("*** ERROR: forking child process failed\n");
      exit(1);
 }
if ((pid2 = fork()) < 0) {    
      printf("*** ERROR: forking child process failed\n");
      exit(1);
 }
if (pid==0) {
    close(1);     
    dup(pfds[1]);  
    close(pfds[0]); 
close(pfds[1]);
    if(execvp(argv[0],argv)<0){
        printf("**error in exec");
    }
} 
else if(pid2==0){

    close(0);       
    dup(pfds[0]);  
    close(pfds[1]);
close(pfds[0]);
    if(execvp(args[0],args)<0){
    printf("**error in exec");

}
}
else{
    close(pfds[0]);
    close(pfds[1]);
    while (wait(&status) != pid)  ;
    while (wait(&status2) != pid2)  ;
        }
}

我很确定没有杂散打印,目录中只有一个 a.out。

【问题讨论】:

    标签: c pipe output


    【解决方案1】:

    您在父进程和第一个子进程中运行第二个fork如果pid 不为零,您应该只进行第二次分叉。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多