简体   繁体   English

父/子fork()和C中的管道

[英]Parent/Child fork() and pipes in C

I need to implement unix codes into my C code, such as PS, WC, and grep. 我需要在我的C代码中实现unix代码,例如PS,WC和grep。 I have pipes and forks that create a child to do each part of the code, however, I am getting a bit confused about what number processes need to be closed each time. 我有创建一个子级来完成代码各部分的管道和叉子,但是,对于每次需要关闭多少个进程,我感到有些困惑。 Here is my code so far, but obviously it doesn't work because the rights things aren't being closed. 到目前为止,这是我的代码,但是显然不能正常工作,因为未关闭权限。

int main() {
int pfd[2];
int pid;

if (pipe(pfd) == -1) {
    perror("pipe failed");
    exit(-1);
}
if ((pid = fork()) < 0) {
    perror("fork failed");
    exit(-2);
}
if (pid == 0) {
    close(pfd[1]);
    dup2(pfd[0], 0);
    close(pfd[0]);
    if (pipe(pdf) == -1) {
        perror("pipe failed");
        exit(-1);
    }
    if (pid ==0) {
        close(pfd[1]);
        dup2(pfd[0], 0);
        close(pfd[0]);
        execlp("wc", "wc", (char *) 0);
        perror("wc failed");
        exit(-3);
    }
    else 
        close(pfd[1]);
        dup2(pfd[0], 0);
        close(pfd[0]);
        execlp("grep", "grep" "1111", (char *) 0);
        perror("grep failed");
        exit(-3);
} 
else {
    close(pfd[0]);
    dup2(pfd[1], 1);
    close(pfd[1]);
    execlp("ps", "ps", "auxj", (char *) 0);
    perror("ps failed");
    exit(-4);
}
exit(0);
}

any help would be great 任何帮助都会很棒

There's no guarantee in the order of execution of the fork'ed processes you are creating. 无法保证您正在创建的派生流程的执行顺序。 This means you can't really close the pipes. 这意味着您无法真正关闭管道。 In order to to so, you would need to add some synchronization, to assure you will have to wait for all the processes that use the pipes to finish and just then close them in the last process alive. 为此,您需要添加一些同步,以确保您必须等待使用管道的所有进程完成,然后在最后一个活动的进程中关闭它们。

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

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