2013-03-10 25 views
1

我想要做的是使用pipe1從父項到子項發送隨機數。然後子進程exec sort程序將這些數字排序並使用pipe2發送回父進程。現在我可以從stdout中得到正確的排序結果,如果我註釋掉「if(pipe2In> = 0){dup2(pipe2In,1); close(pipe2In);}」但我無法從父項中的pipe2中讀取它們,如下所示。實際上,讀取的調用不能返回。我錯過了什麼嗎?感謝任何幫助。如何將「排序」程序的輸出從子項重定向到父項

const int READ = 0, WRITE = 1; 
{ 
pid_t pid; 
int pipe1[2], pipe2[2]; 

if (pipe(pipe1)) 
{ 
    cerr << "Error! Pipe 1 Failed. errno = "<< errno << endl; 
    exit(1); 
} 

int pipe1In = pipe1[WRITE]; 
int pipe1Out = pipe1[READ]; 

if (pipe(pipe2)) 
{ 
    cerr << "Error! Pipe 2 Failed. errno = "<< errno << endl; 
    exit(1); 
} 
int pipe2In = pipe2[WRITE]; 
int pipe2Out = pipe2[READ]; 

pid = fork(); 
if(pid < 0) 
{ 
    cerr << "Error! Fork Failed!\n"; 
    exit(1); 
} 
else if (pid == 0) // child 
{ 
    close(pipe1In); 
    close(pipe2Out); 

    if(pipe1Out >= 0) 
    { 
     dup2(pipe1Out, 0); 
     close(pipe1Out); 
    } 
    if(pipe2In >= 0) 
     { 
      dup2(pipe2In, 1); 
     close(pipe2In); 
    } 

    execlp("sort", "sort", "-nr", (char *)NULL); 
    cerr << "Error - Exec Failed!\n"; 
    exit(-2); 
} // end of child 


close(pipe1Out);   // parent continues from here 
close(pipe2In); 

// generate random numbers 
int rn, tem, i, len; 
for (i = 0; i < nWks; i++) 
{ 
    rn = rand(); 
    tem = rn; 
    len = 1; 
    while (tem /= 10) len++; 
    char *bufWrite = (char *) malloc(len+1); 
     sprintf(bufWrite, "%d\n", rn); 
    write(pipe1In, bufWrite, len+1); 
} 
char bufRead[1024]; 
int n; 
while (n = read(pipe2Out, bufRead, sizeof(bufRead)) != 0) 
{ 
    printf("read count %d\n", n); 
} 
} 

回答

2

sort,直到它在它的輸入流接收EOF不給任何輸出。爲了觸發這種情況,在你的父進程中,你應該在讀循環之前使用close(pipe1In);

+0

工作,謝謝! – user2153006 2013-03-10 17:21:24

相關問題