C - 使用管道模拟 Linux 命令不起作用



我是Linux的新手,并与C一起使用管道。我正在尝试编写执行命令的程序:使用管道ps aux | grep root | wc -l

问题是我的程序在终端中没有显示任何内容,不像原始命令!

这是我的代码:

#include <stdlib.h> // exit
#include <stdio.h>  // printf
#include <unistd.h> // execlp
int main(int argc, char *argv[]) {
int p1[2], p2[2];
int f1, f2;
if(pipe(p1) == -1) {
    exit(1);
}
if(pipe(p2) == -1) {
    exit(2);
}
f1 = fork();
if(f1 < 0) {
    exit(1);
} else if(f1 == 0) {
    close(p1[1]);
    close(0);
    dup2(p1[0], 0);
    close(p1[0]);
    close(p2[0]);
    close(1);
    dup2(p2[1], 1);
    close(p2[1]);
    execlp("grep", "grep", "root", NULL);
} else {
    f2 = fork();
    if(f2 < 0) {
        exit(2);
    } else if(f2 == 0) {
        close(p2[1]);
        close(0);
        dup2(p2[0], 0);
        close(p2[0]);
        execlp("wc", "wc", "-l", NULL);
    } else {
        close(p1[0]);
        close(1);
        dup2(p1[1], 1);
        close(p1[1]);
        execlp("ps", "ps", "aux", NULL);
    }
}
}
#include <stdlib.h> 
 #include <stdio.h>  
 #include <unistd.h> 
 #include <sys/wait.h>
int main(int argc, char *argv[]) 
{
    int p1[2], p2[2];
    int f1, f2, f3;
    if(pipe(p1) == -1) {
        exit(1);
    }   
    f1 = fork();
    if(f1 < 0) {
        exit(1);
    } 
    else if(f1 == 0) {
        dup2(p1[1], 1);
        close(p1[0]);
        close(p1[1]);
        execlp("ps", "ps", "aux", NULL);
        perror("ps");
        exit(1);
    }
    if(pipe(p2) == -1) {
        exit(1);
    }
    f2 = fork();
    if(f2 < 0) {
        exit(1);
    } 
    else if(f2 == 0) {
        dup2(p1[0], 0);
        close(p1[0]);
        close(p1[1]);
        dup2(p2[1], 1);
        close(p2[0]);
        close(p2[1]);
        execlp("grep", "grep", "root", NULL);
        perror("grep");
        exit(1);
    }
    f3 = fork();
    if(f3 < 0) {
        exit(1);
    } 
    else if(f3 == 0) {
        dup2(p2[0], 0);
        close(p2[0]);
        close(p2[1]);
        close(p1[0]);
        close(p1[1]);
        execlp("wc", "wc", "-l", NULL);
        perror("wc");
        exit(1);
    }
    close(p1[0]);
    close(p1[1]);
    close(p2[0]);
    close(p2[1]);
    wait(NULL);
    wait(NULL);
    wait(NULL);
}

最新更新