[英]Why does opening a named pipe non-blockingly return an invalid file descriptor?
我試圖鞏固我對誰阻止何時,為什么阻止打開,寫入和讀取命名管道的理解。
下面的代碼暗示使用O_WRONLY | O_NONBLOCK
打開命名管道是無效的O_WRONLY | O_NONBLOCK
O_WRONLY | O_NONBLOCK
,但是我不確定我的代碼中是否只有一些我不理解的錯誤,或者這通常是真的。
// main.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main( int argc, char* argv[] )
{
int wfd = open( "/tmp/foo", O_WRONLY | O_NONBLOCK );
printf( "wfd[%d]\n", wfd );
if ( wfd >= 0 )
{
int res = write( wfd, "0", 1 );
printf( "write: [%d], errno[%d(%s)]\n", res, errno, strerror( errno ) );
sleep(3);
printf( "writer ending!\n" );
}
return 0;
}
> ls -l /tmp/foo
prwxrwxrwx. 1 user user 0 Sep 4 10:35 /tmp/foo
>
> gcc -g main.c && ./a.out
wfd[-1]
問題 :為什么用O_WRONLY | O_NONBLOCK
打開命名管道? O_WRONLY | O_NONBLOCK
返回無效的文件描述符?
我懷疑這與需要同時打開讀取端和寫入端的管道有關,而我頑固解決這一問題的方法(通過無阻塞地打開一端)因此失敗。 但是我找不到任何支持該假設或以其他方式解釋此觀察結果的特定文檔。
John的答案是正確的,但是要解決您的特定問題,並不是“返回無效的文件描述符”。 open
返回-1表示錯誤。 在這種情況下,您可以檢查errno
(就像您正在執行write
)以查看錯誤原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.