- 论坛徽章:
- 0
|
apue介绍FIFO 时,提到关于open FIFO 时O_NONBLOCK标志位对read()系统调用的影响
When we open a FIFO, the nonblocking flag (O_NONBLOCK) affects what happens.
In the normal case (O_NONBLOCK not specified), an open for read-only blocks until some other process opens the FIFO for writing. Similarly, an open for write-only blocks until some other process opens the FIFO for reading.
If O_NONBLOCK is specified, an open for read-only returns immediately. But an open for write-only returns 1 with errno set to ENXIO if no process has the FIFO open for reading.
我写了一个测试程序,想测试一下 红色标识 部分的内容
可是我发现这种阻塞情况并没有发生
测试程序如下
- #include <stdio.h>
- #include <sys/stat.h>
- #include <string.h>
- #include <errno.h>
- #include <sys/fcntl.h>
- int main(void)
- {
- int fd;
- int n;
- int flag;
- char line[1024];
- if (mkfifo("./test.txt", 0666) == -1)
- {
- printf("mkfifo() error\n:%s\n", strerror(errno));
- exit(0);
- }
- printf("open for read-only and with O_NONBLOCK set\n");
- if ((fd = open("./test.txt", O_RDONLY | O_NONBLOCK)) == -1)
- {
- printf("open error\n");
- exit(0);
- }
- if ((n = read(fd, line, 1024)) == 0)
- {
- printf("read() returned immediately\n");
- }
- else if (n < 0)
- {
- printf("read() error\n");
- }
- else
- {
- line[n] = 0;
- printf("read something:%s\n", line);
- }
- if ((flag = fcntl(fd, F_GETFL, 0)) == -1)
- {
- printf("fcntl() error for F_GETFL\n");
- exit(0);
- }
- printf("open for read-only, with O_NONBLOCK clear\n");
- flag &= ~O_NONBLOCK;
- if (fcntl(fd, F_SETFL, flag) == -1)
- {
- printf("fcntl() error for F_SETFL\n");
- exit(0);
- }
- if ((n = read(fd, line, 1024)) == 0)
- {
- printf("read() returned immediately\n");
- }
- else if (n < 0)
- {
- printf("read() error\n");
- }
- else
- {
- line[n] = 0;
- printf("read something:%s\n", line);
- }
- return 0;
- }
复制代码
运行结果如下:
open for read-only and with O_NONBLOCK set
read() returned immediately
open for read-only, with O_NONBLOCK clear
read() returned immediatel
[ 本帖最后由 zhuhefang2006 于 2009-2-6 17:30 编辑 ] |
|