【问题标题】:piping in shell implementation in C在 C 中的 shell 实现中的管道
【发布时间】:2012-11-16 18:41:42
【问题描述】:

我正在用 C 实现一个 shell。这是我用于管道的函数。当我在代码中输入“ls | a”(即用无效命令传递有效命令)时,它不会像应有的那样退出子进程。我如何让它回到主要功能? 当我做 ps | 时也会发生同样的事情ls或ps | pwd 等,但 ls | ps 的工作方式与 bash 相同。我知道ls | ps或ps | ls 没有意义,但至少它们应该提供与 bash 相同的输出。

void exec3(char **args, char **args2){
    int fd[2];
    pid_t pid,pid1;
    int status;
    pipe(fd);
    int e=0;
    if ((pid = fork()) < 0) {    
        printf("*** ERROR: forking child process failed\n");
        exit(1);
    }

    else if ((pid1 = fork()) < 0) {    
        printf("*** ERROR: forking child process failed\n");
        exit(1);
    }

    else if (pid == 0 && pid1!=0){   
        printf("in 1\n");
        close(1);
        dup(fd[1]);
            close(fd[0]);
        close(fd[1]);

            if(execvp(args[0],args)<0){
                printf("**error in exec");
                close(fd[0]); 
                close(fd[1]);           
                exit(1);
            }
    //printf("exiting 1\n");
    exit(0);
}

else if (pid1 == 0 && pid!=0) {   
    printf("in 2\n");
    close(0);
    dup(fd[0]);
    close(fd[1]);
    close(fd[0]);
    if((e=execvp(args2[0],args2))<0){
            printf("**error in exec2 ");
            close(fd[0]);
            close(fd[1]);

        exit(1);
    }
    exit(0);
}

else {  
        close(fd[0]);
        close(fd[1]);
        fflush(stdout) ;             
        while (wait(&status) != pid);
        while (wait(&status) != pid1);
    }  
}

【问题讨论】:

  • 阅读advancedlinuxprogramming.com之类的好书,研究sash之类的一些小型免费软件shell的源代码。
  • 快速提问:你是 Epitech 的吗? :)
  • 错误信息属于标准错误。 printf( "ERROR...总是是错误的。 perror 是你的朋友。

标签: c shell pipe


【解决方案1】:

您已接近解决方案。看看popen()is implemented是怎么做的。

【讨论】:

  • 其实我找到了,但它非常复杂,超出了我的水平。如果您能指出错误,我将不胜感激。
猜你喜欢
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 2013-03-21
  • 1970-01-01
  • 2013-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多