2011-10-22 49 views
1
#include <unistd.h> 
#include <stdio.h> 


int main(int argc, char* argv[]) 
{ 

    int f1[2], f2[2]; 
    char buff; 

    if(pipe(f1) != -1); 
    printf("Pipe1 allright! \n"); 

    if(pipe(f2) != -1); 
    printf("Pipe2 allright \n"); 



    if(fork()==0) 
    { 
    close(1); 
    dup(f1[1]); 
    close(0); 
    execlp("ls", "ls", "-l", NULL); 
    } 
    else 
    { 
    if(fork()==0) 
    { 
    close(0); 
    dup(f1[0]); 
    close(1); 
    dup(f2[1]); 
    execlp("grep", "grep", "^d", NULL); 
    } 
    else 
    { 
     if(fork()==0) 
     { 
      close(0); 
      dup(f2[0]); 
      execlp("wc", "wc", "-l", NULL); 
     } 
    } 

    } 

    return 0; 

} 

我正在尝试执行ls -l | grep^d | wc -l in C.fork,execlp在Linux中

我试过每一个...

什么是错? :(

输出:PIPE1好吧!Pipe2好吧

PS你们的职位没有什么太大的上下文解释代码段;请更清楚地解释您的方案

+0

'Ps'给我们写信,还是提醒自己? –

+0

它适合我。对不起 – Domiik

+0

你为什么要手动?你为什么不简单地使用'system(“ls -l | grep'^ d'| wc -l”);'? –

回答

3

有几个问题与您的代码:

if(pipe(f1) != -1); 
    printf("Pipe1 allright! \n"); 

我想这应该是一个真正的检查错误,请在if行删除;

运行你的程序之后,你会注意到,grepwc命令仍然存在,它们不会终止。请使用ps(1)命令进行检查。 ls命令似乎已经终止。

假设,四个过程的PID是:

  • 9000(主)
  • 9001(LS)
  • 9002(grep的)
  • 9003(WC)

纵观/proc/9002/fd您会看到,该文件句柄0(stdin)仍然可以阅读:

> ll /proc/9002/fd/0 
lr-x------ 1 as as 64 2011-10-22 20:10 0 -> pipe:[221916] 

环视,谁拥有该句柄仍在

> ll /proc/*/fd/* 2>/dev/null | grep 221916 

你会看到打开,那许多处理这个管道是开放的:既grepwc有他们的开放。其他管柄同样如此。

解决方案:

您必须关闭管道处理后dup严格。看这里:

#include <unistd.h> 
#include <stdio.h> 


int main(int argc, char* argv[]) 
{ 
    int f1[2]; 
    char buff; 

    if(pipe(f1) != -1) 
      printf("Pipe1 allright! \n"); 

    int pid = fork(); 
    if(pid==0) 
    { 
      close(1); 
      dup(f1[1]); 

      close(f1[0]); 
      close(f1[1]); 

      close(0); 
      execlp("ls", "ls", "-l", NULL); 
    } 
    printf("ls-pid = %d\n", pid); 

    int f2[2]; 
    if(pipe(f2) != -1) 
      printf("Pipe2 allright \n"); 

    pid = fork(); 
    if(pid==0) 
    { 
      close(0); 
      dup(f1[0]); 

      close(f1[0]); 
      close(f1[1]); 

      close(1); 
      dup(f2[1]); 

      close(f2[0]); 
      close(f2[1]); 

      execlp("grep", "grep", "^d", NULL); 
      // system("strace grep '^d'"); exit(0); 
    } 
    printf("grep-pid = %d\n", pid); 

    close(f1[0]); 
    close(f1[1]); 

    pid = fork(); 
    if(pid==0) 
    { 
      close(0); 
      dup(f2[0]); 
      close(f2[0]); 
      close(f2[1]); 

      execlp("wc", "wc", "-l", NULL); 
    } 
    printf("wc-pid = %d\n", pid); 

    close(f2[0]); 
    close(f2[1]); 
} 
1

你可能想使用!。 DUP2而不是DUP,就是代替

close(1); 
dup(f1[1]); 

dup2(f1[1], 1); 

等其他occurencies

+0

@Domiik:令人惊讶的是,_this_解决了你的问题。如果我修改问题中的代码,那么仍然没有输出。 –