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

标签 c unix freebsd

我需要将unix代码实现到我的C代码中,例如PS、WC和grep。我有管道和 fork 来创建一个子进程来执行代码的每个部分,但是,我对每次需要关闭的进程数感到有点困惑。到目前为止,这是我的代码,但显然它不起作用,因为权利的事情没有被关闭。

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);
}

任何帮助都会很棒

最佳答案

无法保证您正在创建的 fork 进程的执行顺序。这意味着您无法真正关闭管道。为此,您需要添加一些同步,以确保您必须等待所有使用管道的进程完成,然后在最后一个进程中关闭它们。

关于c - C 中的父/子 fork() 和管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19713332/

相关文章:

exception - 精确异常

node.js - 针对 FreeBSD/etc/master.passwd 进行验证

c - 错误_SDL_Main SDL Mac Xcode 6 C 语言

c - STM32F103RC TIM3 不工作

linux - 使用 Sed 删除空格

linux - 限制用户访问 linux/ubuntu 中的特定目录

mysql - 无法启动mysql服务器

c - Int 指针不为空,可以打印但不能在不抛出段错误的情况下传递到函数中

c - 我不知道我的程序中有什么错误,循环不会停止,请检查它

c - 自毁过程 Unix C