2016-12-03 16 views
0

我是Linux新手,並與管道使用C. 我試圖編寫一個程序執行命令:ps aux | grep root | wc -l使用管道。模擬linux命令與管道不工作

問題是我的程序沒有在終端顯示任何東西,不像原來的命令!

這裏是我的代碼:

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

    } 

} 

} 
+0

刪除問候[會議](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-被刪除從帖子) –

回答

0
#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); 
} 
+0

非常感謝兄弟:) – Stoufa

+0

一些評論,以支持這個答案,並解釋它解決了什麼,總是比禿頭代碼更好。 –

+0

他創建了3個線程,每個線程執行一個命令,而我創建了2個線程,第3個命令由主線程執行!請注意,execlp()會將該線程的代碼替換爲該命令的代碼!也許這就是我的代碼問題,和平:) – Stoufa