用一系列命令管道

时间:2014-06-29 22:26:30

标签: c fork pipe execvp dup

我有一个函数,它接受一个字符串数组和数组的大小。我有一个循环,将字符串标记为命令和争论,然后分叉并逐个执行命令。对于每个命令,我需要将输出传递给下一个命令输入。我不完全确定我的dup / close电话是否正确。任何帮助,将不胜感激。如果数组中只有一个命令,我将它设置为不管道。

void runcmds(char **cmds, int count){
    int fd[2];
    int index;
    pid_t pID;
    for (index = 0; index < count; index++){
        //tokenize string
        token *newToken = mytoken(cmds[index]);
        if (count > 1){ //pipe if more than one command
            pipe(fd);
        }
        pID = fork();
        if (pID < 0){ //fork failed
           printf("Error: fork\n");
           exit(1);
        }
        else if (pID == 0){
            if (count == 1){
                ; //no need to pipe
            }
            //if first command of multiple commands
            else if ((index == 0) && (count > 1)){
                close(1); //close stdout
                dup(fd[1]); //replace stdout with pipe write
                close(fd[0]);//close pipe read
            }
            //if last command
            else if (index == (count - 1)){
                close(0); //close stdin
                dup(fd[0]); //replace stdin with pipe read
                close(fd[1]); //close pipe write
            //if middle command
            else{
                close(0);
                dup(fd[0]);
                close(1);
                dup(fd[1]);
            }
            //execute command
            if (execvp(newToken->command, newToken->args) < 0){
                //execvp failed
                printf("Error: execvp\n");
                exit(1);
             }
        }
        waitpid(pID, NULL, 0);
        if ((index == 0) && (count > 1)){
            close(fd[1]);
        }
        else if (index == (count - 1)){
            close(fd[0]);
        }
        else{
             ; //middle commands need both open
        }
    }
    return;
}

0 个答案:

没有答案