结论
一、当前为了读而打开 FIFO 时
O_NONBLOCK disable:open 调用阻塞,直到有进程为写而打开该 FIFO
O_NONBLOCK enable: open 调用返回文件描述符
二、当前为了写而打开 FIFO 时
O_NONBLOCK disable:open 调用阻塞,直到有进程为读而打开该 FIFO
O_NONBLOCK enable: open 调用返回 -1,errno 值为 ENXIO(6)
验证如下:
1、O_NONBLOCK disable:open 调用阻塞,直到有进程为写而打开该 FIFO
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MYFIFO "./myfifo"
int main()
{
int fd = -1;
if (-1 == access(MYFIFO, F_OK)
&& -1 == mkfifo(MYFIFO, 0664))
{
perror("mkfifo error");
return EXIT_FAILURE;
}
fd = open(MYFIFO, O_RDONLY);
printf("open %s for reading, fd: %d\n", MYFIFO, fd);
if (fd >= 0)
close(fd);
return 0;
}
2、O_NONBLOCK enable: open 调用返回文件描述符
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MYFIFO "./myfifo"
int main()
{
int fd = -1;
if (-1 == access(MYFIFO, F_OK)
&& -1 == mkfifo(MYFIFO, 0664))
{
perror("mkfifo error");
return EXIT_FAILURE;
}
fd = open(MYFIFO, O_RDONLY | O_NONBLOCK);
printf("open %s for reading, fd: %d\n", MYFIFO, fd);
if (fd >= 0)
close(fd);
return 0;
}
/*
* open ./myfifo for reading, fd: 3
*/
3、O_NONBLOCK disable:open 调用阻塞,直到有进程为读而打开该 FIFO
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MYFIFO "./myfifo"
int main()
{
int fd = -1;
if (-1 == access(MYFIFO, F_OK)
&& -1 == mkfifo(MYFIFO, 0664))
{
perror("mkfifo error");
return EXIT_FAILURE;
}
fd = open(MYFIFO, O_WRONLY);
printf("open %s for writing, fd: %d\n", MYFIFO, fd);
if (fd >= 0)
close(fd);
return 0;
}
4、O_NONBLOCK enable: open 调用返回 -1,errno 值为 ENXIO(6)
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MYFIFO "./myfifo"
int main()
{
int fd = -1;
if (-1 == access(MYFIFO, F_OK)
&& -1 == mkfifo(MYFIFO, 0664))
{
perror("mkfifo error");
return EXIT_FAILURE;
}
fd = open(MYFIFO, O_WRONLY | O_NONBLOCK);
if (fd < 0)
{
perror("open error");
printf("errno: %d\n", errno);
return EXIT_FAILURE;
}
printf("open %s for writing, fd: %d\n", MYFIFO, fd);
if (fd >= 0)
close(fd);
return 0;
}
/*
* open error: No such device or address
* errno: 6
*/