很奇怪!我尝试了一段代码,它在不使用O_NONBLOCK的情况下打开文件,然后分为3个阶段进行。第三个阶段没有正确执行,尽管O_NONBLOCK标志已被重置!
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
char buf[1024];
int rd;
const char* fn = "prova.txt";
int i = mkfifo(fn, 0666);
int fd = open(fn, O_RDONLY);
int flags = fcntl(fd, F_GETFL);
printf("1) Waits!\t\tflags=0%08o\n",flags);
rd= read(fd, buf, 100);
printf("%d %o\n",rd,flags);
flags |= O_NONBLOCK;
printf("2) Doesn't wait!\tflags=0%08o\n",flags);
fcntl(fd, F_SETFL, flags);
rd= read(fd, buf, 100);
printf("%d %o\n",rd,flags);
flags &= ~O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
flags=fcntl(fd, F_GETFL);
printf("3) Waits!\t\tflags=0%08o\n",flags);
rd= read(fd, buf, 100);
printf("%d %o\n",rd,flags);
puts("End!");
return 0;
}
以下是命令序列和输出结果:
sergio@zarathustra:~$ ./a.out &
[2] 6555
sergio@zarathustra:~$ echo xxx >> prova.txt
1) Waits! flags=000100000
4 100000
2) Doesn't wait! flags=000104000
0 104000
3) Waits! flags=000100000
0 100000
End!
sergio@zarathustra:~$
cout << rd << endl;
是纯C++,但是所有的解释都在之前的链接中 https://dev59.com/yHE85IYBdhLWcg3wbS1h - Ôrelflags &= ~O_NONBLOCK;
之前/之后检查过flags
,以确保按位取反实现了你需要的功能?为什么不在第二次调用fcntl
时将O_RDONLY
设置为flags
进行测试呢? - David C. Rankin