[英]read fifo: why is it blocking then non-blocking
我正在使用FIFO使兩個進程進行通信。
//client:
const char * msg = "Hello, I'm cleint1.";
const char * fifoName = "../server/fifo.tmp";
int fd = open(fifoName, O_WRONLY);
write(fd, msg, strlen(msg) + 1);
close(fd);
//server:
char msg[100];
const char * fifoName = "fifo.tmp";
mkfifo(fifoName, 0666);
int fd = open(fifoName, O_RDONLY);
while(read(fd, msg, 100) > 0)
{
std::cout<<"msg received: "<<msg<<std::endl;
}
close(fd);
unlink(fifoName);
服務器將首先在fifoName
阻止以等待fifoName
某些消息。 當一些消息到來(客戶端已執行)時,服務器將讀取它們,然后循環將結束。
我現在很困惑。 因為我無法弄清楚為什么服務器第一次調用read
會阻塞,而在再次調用read
時卻不再阻塞。
我打印read
的返回值,並在收到第一條消息后得到0。
我需要的是每次都阻止read
以使服務器可以在某些客戶端發送消息后立即接收任何消息。
您得到0作為指標,因為管道的另一端被關閉,所以沒有剩余數據,也沒有更多數據。
我假設您希望服務器能夠堅持住並處理多個客戶端,甚至可能同時進行。
管道根本上不適合該目的。 您想改用unix套接字 。
最后,像這樣的循環:
while(read(fd, msg, 100) > 0)
{
std::cout<<"msg received: "<<msg<<std::endl;
}
從根本上講是錯誤的。 由於信號到來,很容易從讀取中獲取錯誤。
還要注意,對於緩沖區大小重復使用“ 100”,而不是使用sizeof(msg),這違反了DRY。
您可以簡單地重試讀取。 例如
int iResult;
do
{
iResult = read(fd, buffer, size);
if (0 == iResult)
{
// Skip to the end of the do loop
continue;
}
// Handle real errors
} while (!condition);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.