在C中实现多个管道

时间:2011-12-05 17:08:21

标签: c linux shell pipe

我正在尝试在C中的shell中实现多个管道。我找到了关于这个website的教程,我所做的功能基于这个例子。这是函数

void executePipes(cmdLine* command, char* userInput) {
    int numPipes = 2 * countPipes(userInput);
    int status;
    int i = 0, j = 0;
    int pipefds[numPipes];

    for(i = 0; i < (numPipes); i += 2)
        pipe(pipefds + i);

    while(command != NULL) {
        if(fork() == 0){

            if(j != 0){
                dup2(pipefds[j - 2], 0);
            }

            if(command->next != NULL){
                dup2(pipefds[j + 1], 1);
            }    

            for(i = 0; i < (numPipes); i++){
                close(pipefds[i]);
            }
            if( execvp(*command->arguments, command->arguments) < 0 ){
                perror(*command->arguments);
                exit(EXIT_FAILURE);
            }
        }

        else{
                if(command != NULL)
                    command = command->next;

                j += 2;
                for(i = 0; i < (numPipes ); i++){
                   close(pipefds[i]);
                }
               while(waitpid(0,0,0) < 0);
        }
    }

}

执行它并输入类似ls | grep bin之类的命令后,shell只挂起并且不输出任何结果。我确保关闭所有管道。但它只是挂在那里。我以为waitpid就是问题所在。我删除了waitpid,执行后我没有得到任何结果。我做错了什么?感谢。

添加了代码:

void runPipedCommands(cmdLine* command, char* userInput) {
    int numPipes = countPipes(userInput);

    int status;
    int i = 0, j = 0;

    pid_t pid;

    int pipefds[2*numPipes];

    for(i = 0; i < 2*(numPipes); i++){
        if(pipe(pipefds + i*2) < 0) {
            perror("pipe");
            exit(EXIT_FAILURE);
        }
    }

    while(command) {
        pid = fork();
        if(pid == 0) {

            //if not first command
            if(j != 0){
                if(dup2(pipefds[(j-1) * 2], 0) < 0){
                    perror(" dup2");///j-2 0 j+1 1
                    exit(EXIT_FAILURE);
                    //printf("j != 0  dup(pipefd[%d], 0])\n", j-2);
                }
            //if not last command
            if(command->next){
                if(dup2(pipefds[j * 2 + 1], 1) < 0){
                    perror("dup2");
                    exit(EXIT_FAILURE);
                }
            }

            for(i = 0; i < 2*numPipes; i++){
                    close(pipefds[i]);
            }

            if( execvp(*command->arguments, command->arguments) < 0 ){
                    perror(*command->arguments);
                    exit(EXIT_FAILURE);
            }
        } else if(pid < 0){
            perror("error");
            exit(EXIT_FAILURE);
        }

        command = command->next;
        j++;
    }
        for(i = 0; i < 2 * numPipes; i++){
            close(pipefds[i]);
            puts("closed pipe in parent");
        }

        while(waitpid(0,0,0) <= 0);

    }

}

6 个答案:

答案 0 :(得分:14)

我认为这里的问题是你在创建孩子的同一循环中等待和关闭。在第一次迭代中,子进程将执行exec(这会破坏子程序,用第一个命令覆盖它),然后父进程关闭所有文件描述符并等待子进程在迭代创建下一个子进程之前完成。此时,由于父级已关闭所有管道,因此任何其他子级都无需写入或读取。由于您没有检查dup2调用是否成功,因此不会注意到这一点。

如果要保持相同的循环结构,则需要确保父级只关闭已经使用过的文件描述符,但保留那些尚未单独使用的文件描述符。然后,在创建所有子项后,您的父级可以等待。

编辑:我在答案中混淆了父/子,但原因仍然存在:继续进行分叉的过程将关闭所有管道副本,因此任何进程都在第一个fork没有有效的文件描述符来读取/写入。

伪代码,使用预先创建的管道数组:

/* parent creates all needed pipes at the start */
for( i = 0; i < num-pipes; i++ ){
    if( pipe(pipefds + i*2) < 0 ){
        perror and exit
    }
}

commandc = 0
while( command ){
    pid = fork()
    if( pid == 0 ){
        /* child gets input from the previous command,
            if it's not the first command */
        if( not first command ){
            if( dup2(pipefds[(commandc-1)*2], 0) < ){
                perror and exit
            }
        }
        /* child outputs to next command, if it's not
            the last command */
        if( not last command ){
            if( dup2(pipefds[commandc*2+1], 1) < 0 ){
                perror and exit
            }
        }
        close all pipe-fds
        execvp
        perror and exit
    } else if( pid < 0 ){
        perror and exit
    }
    cmd = cmd->next
    commandc++
}

/* parent closes all of its copies at the end */
for( i = 0; i < 2 * num-pipes; i++ ){
    close( pipefds[i] );
}

在此代码中,原始父进程为每个命令创建一个子进程,因此可以在整个考验中幸存下来。孩子们检查他们是否应该从上一个命令获得他们的输入,以及他们是否应该将他们的输出发送到下一个命令。然后他们关闭所有管道文件描述符的副本,然后执行exec。父进程除了为每个命令创建一个子进程之前不进行任何操作。然后关闭描述符的所有副本,然后继续等待。

首先创建所需的所有管道,然后在循环中管理它们是棘手的,需要一些数组算法。不过,目标看起来像这样:

cmd0    cmd1   cmd2   cmd3   cmd4
   pipe0   pipe1  pipe2  pipe3
   [0,1]   [2,3]  [4,5]  [6,7]

意识到,在任何给定的时间,您只需要两组管道(前一个命令的管道和下一个命令的管道)将简化您的代码并使其更加健壮。 Ephemient为此here提供了伪代码。他的代码更干净,因为父代和子代不必进行不必要的循环来关闭不需要的文件描述符,因为父代可以在fork之后立即轻松地关闭文件描述符的副本。

作为旁注:您应该始终检查pipe,dup2,fork和exec的返回值。

编辑2 :伪代码中的拼写错误。 OP:num-pipes将是管道数量。例如,“ls | grep foo | sort -r”将有2个管道。

答案 1 :(得分:7)

这是正确的功能代码

void runPipedCommands(cmdLine* command, char* userInput) {
    int numPipes = countPipes(userInput);


    int status;
    int i = 0;
    pid_t pid;

    int pipefds[2*numPipes];

    for(i = 0; i < (numPipes); i++){
        if(pipe(pipefds + i*2) < 0) {
            perror("couldn't pipe");
            exit(EXIT_FAILURE);
        }
    }


    int j = 0;
    while(command) {
        pid = fork();
        if(pid == 0) {

            //if not last command
            if(command->next){
                if(dup2(pipefds[j + 1], 1) < 0){
                    perror("dup2");
                    exit(EXIT_FAILURE);
                }
            }

            //if not first command&& j!= 2*numPipes
            if(j != 0 ){
                if(dup2(pipefds[j-2], 0) < 0){
                    perror(" dup2");///j-2 0 j+1 1
                    exit(EXIT_FAILURE);

                }
            }


            for(i = 0; i < 2*numPipes; i++){
                    close(pipefds[i]);
            }

            if( execvp(*command->arguments, command->arguments) < 0 ){
                    perror(*command->arguments);
                    exit(EXIT_FAILURE);
            }
        } else if(pid < 0){
            perror("error");
            exit(EXIT_FAILURE);
        }

        command = command->next;
        j+=2;
    }
    /**Parent closes the pipes and wait for children*/

    for(i = 0; i < 2 * numPipes; i++){
        close(pipefds[i]);
    }

    for(i = 0; i < numPipes + 1; i++)
        wait(&status);
}

答案 2 :(得分:2)

(缩短的)相关代码是:

    if(fork() == 0){
            // do child stuff here
            ....
    }
    else{
            // do parent stuff here
            if(command != NULL)
                command = command->next;

            j += 2;
            for(i = 0; i < (numPipes ); i++){
               close(pipefds[i]);
            }
           while(waitpid(0,0,0) < 0);
    }

这意味着父(控制)过程执行此操作:

  • 关闭所有管道
  • 等待子进程
  • next loop / child

但它应该是这样的:

  • 关闭所有管道(一切都应该被骗了)
  • 等待孩子

答案 3 :(得分:0)

基本上你想做的是一个递归函数,其中子进程执行第一个命令而父进程执行第二个命令如果没有其他命令再次调用该函数。

答案 4 :(得分:0)

在Christopher Neylan提到的给定时间内使用最多两个管道的想法的基础上,我整理了n管道的伪代码。 args是一个大小为#args_size&#39;的字符指针数组。这是一个全局变量。

// MULTIPLE PIPES
// Test case:   char *args[] = {"ls", "-l", "|", "head", "|", "tail", "-4", 
0};// "|", "grep", "Txt", 0};   
enum fileEnd{READ, WRITE};

void multiple pipes( char** args){
pid_t cpid;
// declare pipes
int pipeA[2]
int pipeB[2]
// I have done getNumberofpipes
int numPipes = getNumberOfPipes;
int command_num = numPipes+1;
// holds sub array of args 
// which is a statement to execute
// for example: cmd = {"ls", "-l", NULL}
char** cmd 
// iterate over args
for(i = 0; i < args_size; i++){
  // 
  // strip subarray from main array
  //  cmd 1 | cmd 2 | cmd3 => cmd
  // cmd = {"ls", "-l", NULL}
  //Open/reopen one pipe

  //if i is even open pipeB
    if(i % 2)  pipe(pipeB);
  //if i is odd open pipeA
    else       pipe(pipeA);


  switch(cpid = fork(){
      case -1: error forking
      case 0: // child process
            childprocess(i);
      default: // parent process
           parentprocess(i, cpid);
  }
}
}
// parent pipes must be closed in parent
void parentprocess(int i, pid_t cpid){

   // if first command
   if(i == 0)  
        close(pipeB[WRITE]);

   // if last command close WRITE
   else if (i == numPipes){
       // if i is even close pipeB[WRITE]
       // if i is odd close pipeA[WRITE]
   }

   // otherwise if in middle close READ and WRITE 
   // for appropriate pipes
      // if i is even
      close(pipeA[READ])
      close(pipeB[WRITE])
      // if i is odd
      close(pipeB[READ])
      close(pipeA[WRITE])
   }

   int returnvalue, status;
   waitpid(cpid, returnvalue, status);
}
void childprocess(int i){

    // if in first command
    if(i == 0)
        dup2(pipeB[WRITE], STDOUT_FILENO);
    //if in last command change stdin for
    // the necessary pipe. Don't touch stdout - 
    // stdout goes to shell
    else if( numPipes == i){
        // if i is even
        dup2(pipeB[READ], STDIN_FILENO)
        //if i is odd
        dup2(pipeA[READ], STDIN_FILENO);        
    }
    // otherwise, we are in middle command where
    // both pipes are used.
    else{
       // if i is even
       dup2(pipeA[READ], STDIN_FILENO)
       dupe(pipeB[WRITE], STDOUT_FILENO)
       // if i is odd
       dup2(pipeB[READ], STDIN_FILENO)
       dup2(pipeA[WRITE], STDOUT_FILENO)
    }

    // execute command for this iteration
    // check for errors!!
    // The exec() functions only return if an error has occurred. The return value is -1, and errno is set to indicate the error.
    if(exec(cmd, cmd) < 0)
        printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));
    }   
}

答案 5 :(得分:0)

您仅需要两条管道,如下所示:

typedef enum {start, middle, end} pipekind;
typedef int pipe_io[2];
pipe_io file, _file;
pid_t pid;
bool alternate = false;

#define currentpipe (alternate ? _file : file)
#define previouspipe (alternate ? file : _file)
#define nextpipe previouspipe

#define READ 0
#define WRITE 1
#define ERROR -1
#define CHILD 0
#define PARENT default

//call this function inside a loop
void execute(char **command, pipekind kind)
{
    switch (pid = fork())
    {
        case ERROR: perror("fork()"); break;
        case CHILD: 
                if (*command == NULL) exit(EXIT_SUCCESS);
                switch (kind)
                {
                    case start: 
                                dup2(currentpipe[WRITE], STDOUT_FILENO);
                                break;
                    case middle: 
                                dup2(previouspipe[READ], STDIN_FILENO); 
                                dup2(currentpipe[WRITE], STDOUT_FILENO);
                                break;
                    case end:
                                dup2(currentpipe[READ], STDIN_FILENO);
                    default:    break;
                }
                execvp(*command, command);
                perror(*command);
                _exit(EXIT_FAILURE);
        PARENT:
                switch (kind)
                {
                    case start: 
                                close(currentpipe[WRITE]);
                                break;
                    case middle:  
                                close(previouspipe[READ]);
                                close(currentpipe[WRITE]);
                                break;
                    case end: 
                                close(currentpipe[READ]);
                    default:    break;
                }
                while(wait(NULL) > 0);
                getnextpipe(); //not defined in this shorthand example
    }
    alternate = alternate ? false : true;
}

我将link留给需要它的人使用完整的工作代码。