2012-07-09 89 views
1

我正在使用Windows,我正在學習管道,以及它們是如何工作的。如何判斷管道上是否有新數據?

有一件事我還沒有發現是我怎麼能知道,如果有一個管道新的數據(從管道的孩子/接收器端?

通常的方法是有一個線程讀取的數據,並將其發送到被處理:

void GetDataThread() 
{ 
    while(notDone) 
    { 
     BOOL result = ReadFile (pipe_handle, buffer, buffer_size, &bytes_read, NULL); 
     if (result) DoSomethingWithTheData(buffer, bytes_read); 
     else Fail(); 
    } 
} 

的問題是,所述的ReadFile()函數等待數據,然後將其讀出它的存在告知是否有新的數據的方法,而無需實際等待。新數據如下:

void GetDataThread() 
{ 
    while(notDone) 
    { 
     BOOL result = IsThereNewData (pipe_handle); 
     if (result) { 
      result = ReadFile (pipe_handle, buffer, buffer_size, &bytes_read, NULL); 
      if (result) DoSomethingWithTheData(buffer, bytes_read); 
      else Fail(); 
     } 

     DoSomethingInterestingInsteadOfHangingTheThreadSinceWeHaveLimitedNumberOfThreads(); 
    } 
} 
+0

哇...我真的_really_希望你做**不**有一個函數叫做'DoSomethingInterestingInsteadOfHangingTheThreadSinceWeHaveLimitedNumberOfThreads'' ..... – Neal 2012-07-09 14:18:47

+0

@Neal不,我其實寫了整個代碼在這個網站上。 – Tibi 2012-07-09 14:19:46

+0

咦?........... – Neal 2012-07-09 14:20:14

回答

4

使用PeekNamedPipe()

DWORD total_available_bytes; 
if (FALSE == PeekNamedPipe(pipe_handle, 
          0, 
          0, 
          0, 
          &total_available_bytes, 
          0)) 
{ 
    // Handle failure. 
} 
else if (total_available_bytes > 0) 
{ 
    // Read data from pipe ... 
} 
1

還有一個方法是使用IPC同步原語,如事件(CreateEvent())。在與複雜邏輯的進程間通信的情況下 - 你也應該關注它們。

+0

我不需要非常複雜的溝通。現在,我想使用管道創建一個調試系統,並且大部分字符串都將被傳遞。 – Tibi 2012-07-09 18:23:39