2010-04-08 182 views
0

有沒有人看到這個問題,它不工作說壞的文件描述符不知道爲什麼?錯誤的文件描述符

pipe(pipefd[0]); 
if ((opid = fork()) == 0) { 
    dup2(pipefd[0][1],1);/*send to output*/ 
    close(pipefd[0][0]); 
    close(pipefd[0][1]); 
    execlp("ls","ls","-al",NULL); 
} 

if((cpid = fork())==0){ 
    dup2(pipefd[0][1],0);/*read from input*/ 
    close(pipefd[0][0]); 
    close(pipefd[1][1]); 
    execlp("grep","grep",".bak",NULL); 
} 

    close(pipefd[0][0]); 
    close(pipefd[0][1]); 
+2

什麼是對pipefd申報? – jemfinch 2010-04-08 02:36:54

+0

int pipefd [3] [2]; – Luke 2010-04-08 02:39:26

回答

1

基於您的代碼,我猜pipefd被定義爲:

​​

現在,當你這樣做:

​​

這僅填充pipefd[0][0]pipefd[0][1]

所以,當你這樣做:

# Bad descriptor 
close(pipefd[1][1]); 

你引用隨機的垃圾(你永遠不會設置pipefd[1][0]pipefd[1][1])。

從顯示的代碼,我不明白爲什麼你不只是做:

int pipefd[2]; 
pipe(pipefd); 
0

第二個塊中的索引看起來可疑。