2013-03-21 60 views
0

我寫了一段相對簡單的代碼,用於輪詢在子進程中重定向爲標準輸出的管道。但是當輪詢函數返回並且說數據就緒時,讀取函數總是返回零。無法從重定向io讀取數據

是否有任何理由突出說明爲什麼這不起作用?當我直接寫入從子進程到父進程的管道時,它工作正常。我想我只是錯誤地重定向了io。

這裏的父進程代碼:

注:所有宏解釋錯誤,並把它們打印到錯誤日誌。

pollData.fd = out.fd[ READ_INDEX ]; 
pollData.events = POLL_IN; 
pollData.revents = 0; 

printf("Polling pipe for data...\n"); 

if(poll(&pollData, 1, 5000) > 0) 
{ 
     int bytesRead = 0, trys = TRYS; 
     printf("Data has been received: "); 

     Read: 

     bytesRead = read(out.fd[ READ_INDEX ] , out.buf, BUF_SIZE); 

      if(bytesRead > 0) printf("%s" , out.buf); 
     else if(bytesRead < 0) printf("Error receiving data.\n"); 
     else 
     { 
       trys--; 
       printf("No data was read.\n"); 
       sleep(SLEEP); 
       if(trys > 0) goto Read; 
     } 
} 
else LOG(ERR_POLLING, 0); 

這裏的子進程代碼: 注:FD_REPLACE使用DUP2並關閉舊句柄。

FD_CLOSE_PACK( out.fd[ READ_INDEX ], 
       err.fd[ READ_INDEX ], 
       in.fd[ WRITE_INDEX ]); 

FD_REPLACE(fileno(stdout) , out.fd[ WRITE_INDEX ] , Child_Fail); 
FD_REPLACE(fileno(stderr) , err.fd[ WRITE_INDEX ] , Child_Fail); 
FD_REPLACE(fileno(stdin ) , in.fd[ READ_INDEX ] , Child_Fail); 

printf("This is a message from the test program!\n Hope it works!\n"); 

sleep(10); 

Child_Fail: 

FD_CLOSE_PACK( out.fd[ WRITE_INDEX ], 
       err.fd[ WRITE_INDEX ], 
       in.fd[ READ_INDEX ]); 
return -1; 

下面是宏之一:

#define FD_REPLACE(old_fd, fd , addr)   
if(dup2(old_fd, fd) < 0)           
{ 
     LOG(ERR_DUP2, #old_fd " with " #fd);     
     goto addr;   
}   

下面是來自終端的輸出:

Polling pipe for data... 
Data has been received: No data was read. 
No data was read. 
No data was read. 
No data was read. 
No data was read. 

Now closing... 
+0

'poll'返回後'pollData.revents'的值是什麼?它是否設置了「POLLIN」標誌? – 2013-03-21 05:24:41

+0

不,它是16.我正在查找什麼16意味着現在 – tay10r 2013-03-21 05:37:36

+0

這意味着POLLHUP,這似乎意味着設備已斷開連接。 – tay10r 2013-03-21 05:43:35

回答

1

我得到它的工作。我錯誤地替換了文件描述符。我替換了錯誤的描述符,並在我關閉舊描述符之前進行了處理。我上面發佈的代碼顯示了舊的宏。新的宏(沒有錯誤檢查):

#define FD_REPLACE(old_fd, fd, addr) 
close(old_fd); 
dup2(fd, old_fd);