*几乎*完美的C壳管道

Ric*_*Sch 12 c linux shell pipe

我正在用C编写一个小的linux shell,并且非常接近于完成.我接受用户的命令并将其存储在args中,由空格分隔.在下面的示例中,假设args包含以下内容:

args[] = {"ls", "-l", "|", "wc"};

我的函数接受args并且还接受有多少个管道.我尽可能地评论了我的代码.这里是:

int do_command(char **args, int pipes) {
    // The number of commands to run
    const int commands = pipes + 1;
    int i = 0;

    int pipefds[2*pipes];

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

    int pid;
    int status;

    int j = 0;
    int k = 0;
    int s = 1;
    int place;
    int commandStarts[10];
    commandStarts[0] = 0;

    // This loop sets all of the pipes to NULL
    // And creates an array of where the next
    // Command starts

    while (args[k] != NULL){
        if(!strcmp(args[k], "|")){
            args[k] = NULL;
            // printf("args[%d] is now NULL", k);
            commandStarts[s] = k+1;
            s++;
        }
        k++;
    }



    for (i = 0; i < commands; ++i) {
        // place is where in args the program should
        // start running when it gets to the execution
        // command
        place = commandStarts[i];

        pid = fork();
        if(pid == 0) {
            //if not last command
            if(i < pipes){
                if(dup2(pipefds[j + 1], 1) < 0){
                    perror("dup2");
                    exit(EXIT_FAILURE);
                }
            }

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

            int q;
            for(q = 0; q < 2*pipes; q++){
                    close(pipefds[q]);
            }

            // The commands are executed here, 
            // but it must be doing it a bit wrong          
            if( execvp(args[place], args) < 0 ){
                    perror(*args);
                    exit(EXIT_FAILURE);
            }
        }
        else if(pid < 0){
            perror("error");
            exit(EXIT_FAILURE);
        }

        j+=2;
    }

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

    for(i = 0; i < pipes + 1; i++){
        wait(&status);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,当程序样的正确执行,这是奇怪的行为,我希望你能帮助我.

比如说,我跑ls | wc,输出是ls |的输出 wc,但是它也会在它下面打印一个简单ls的输出,即使它应该只是输出的wc.

作为另一个例子,当我尝试ls -l |时 WC,第一数WC显示出来,但随后的输出ls -l命令显示了下方,即使它应该只是在厕所的输出.

提前致谢!:)

jpa*_*cek 8

好的,我发现了一个小错误.这个

       if( execvp(args[place], args) < 0 ){
Run Code Online (Sandbox Code Playgroud)

应该

       if( execvp(args[place], args+place) < 0 ){
Run Code Online (Sandbox Code Playgroud)

您的版本使用args作为所有其他命令的第一个命令.除此之外,它对我有用.