繁体   English   中英

C 中的多进程 Shell,使用管道 [Linux]

[英]Multi-Process Shell in C, using Pipes [Linux]

我正在尝试在 C 中编写 shell 代码,它支持多管道进程处理,具体取决于用户给出的单独进程的数量,每个进程由“|”分隔象征。 shell 将进程数量分叉到每个进程的子进程中。

这是一个例子:

texto1.txt = "Isto é o Texto 1"

$ cat texto1.txt | grep -c Isto 

结果:1

但是我在子进程之间以及最终与父进程之间进行通信时遇到了麻烦。

这是我当前的execpipe function 代码,它执行 pipe 进程, argv1argv2是用户输入给出的 2 个独立进程:(示例: ls -l | wc -l

int execpipe(char ** argv1, char  ** argv2)
{
    int fds[2];
    pipe(fds);
    int i;
    pid_t p1, p2;
    p1 = fork();
    if (p1 == -1)
    { // error
        char * error = strerror(errno);
        printf("error fork!!\n");
        return 1;
    }
    if (p1 == 0)
    { // child process

        close(fds[0]);
        dup2(fds[1], STDOUT_FILENO);
        close(fds[1]);
        if(execvp(argv1[0], argv1)<0){ // run command AFTER pipe character in userinput
            char * error = strerror(errno);
            printf("unknown command\n");
            return 0;
        }
    }
    else
    { // parent process
        p2 = fork();

        if(p2==0){
            close(fds[1]);
            dup2(fds[0], STDIN_FILENO);
            close(fds[0]);
            if(execvp(argv2[0], argv2)<0){ // run command AFTER pipe character in userinput
                char * error = strerror(errno);
                printf("unknown command\n");
                return 0;
            }
        }else{ //Parent waits for both of it's children
            wait(NULL);
            wait(NULL);
        }
    }
}

父进程必须关闭管道的写入端以指示第二个进程不再有数据到来:

            }
        }else{ //Parent waits for both of it's children
            close(fds[1]); // ++ add this line
            wait(NULL);
            wait(NULL);
        }

小注:而不是

        char * error = strerror(errno);
        printf("error fork!!\n");

为什么不

        perror("fork");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM