可以在管道上執行非阻塞的I/O嗎? fcntl無法設置O_NONBLOCK。 Linux編程接口的頁面918包含一個表'從管道或FIFO(p)'讀取n個字節的語義。該表列出了一列標題爲O_NONBLOCK的管道和FIFO的行爲?這意味着你可以在管道上設置O_NONBLOCK標誌。它是否正確?以下代碼未能設置標誌,fcntl(2)雖然不報告錯誤。管道上的非阻塞讀取
#include <fcntl.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define SLEEP 1
int
main(int argc, char *argv[]) {
pid_t childPid;
int pfd[2];
int nread, flags;
int c = 'a';
setbuf(stdout, NULL);
if (pipe(pfd) == -1) {
printf("error: pipe");
exit(EXIT_FAILURE);
}
switch (childPid = fork()) {
case -1:
printf("error: fork");
exit(EXIT_FAILURE);
case 0: /* child */
if (close(pfd[0]) == -1) {
printf("child: close pfd read");
exit(EXIT_FAILURE);
}
sleep(SLEEP);
_exit(EXIT_SUCCESS);
default:
break;
/* parent falls through */
}
if (close(pfd[1]) == -1) {
printf("parent: close pipe write");
exit(EXIT_FAILURE);
}
flags = fcntl(pfd[0], F_GETFD);
flags |= O_NONBLOCK;
if (fcntl(pfd[0], F_SETFD, flags))
perror("fcntl");
/* verify flags set correctly */
flags = fcntl(pfd[0], F_GETFD);
if (!(flags & O_NONBLOCK)) {
printf("failed to set O_NONBLOCK\n");
exit(EXIT_FAILURE);
}
wait(NULL);
exit(EXIT_SUCCESS);
}
它看起來像'F_GETFD'操作中的一個錯誤。我已經確認這確實將描述符設置爲非阻塞,並且操作不會阻塞,但是'F_GETFD'仍然返回零。 –