linux有名管道的使用主要涉及到unlink,mkfifo,read,write,close这几个函数。此处主要讨论下关于O_NONBLOCK标志的影响。函数手册中说道此标志决定是否阻塞读,写操作。我的初步理解是此标志会影响read/write的操作。但是,实际情况好像并不是这样。通过下面的程序和运行结果就可以看到。
#include #include #include #include #include #include #include #include #include int main() { int fd; char buffer[100]; int length; size_t readsz; int pid; unlink("./tmp"); if(mkfifo("./tmp",0777) == -1) { printf("make fifo erro : %s",strerror(errno)); exit(1); } pid = fork(); if(pid > 0) { printf("in the child\n"); fd = open("./tmp",O_RDONLY); sleep(10); memset(buffer,0,100); length = read(fd,buffer,100); printf("read bytes %d\nthe text is \n%s\n",length,buffer); close(fd); exit(1); } else if(pid == 0) { printf("in the father\n"); fd = open("./tmp",O_WRONLY); printf("file id is %d\n",fd); memset(buffer,0,100); printf("please enter msg\n"); length = read(0,buffer,100); length = write(fd,buffer,length); if(length != -1) printf("write ok\n"); close(fd); exit(2); } } /unistd>
下面是运行结果:
in the child
in the father
<此处无停顿>
file id is 3please enter msg
<输入>hello world!<\n>
write ok
<如果从 in the father之后到此处未满10秒,则停顿到10秒,若超过时间则直接打印下面的内容>
read bytes 13
the text is
hello world!<\n>
但是,如果将源码的29行与30行的顺序交换。则运行情况就非常不一样了!
运行时,会在上面的运行结果“in the father"之后停顿10秒,然后才会打印file id is 3 和 please enter msg的信息。
原因是在源程序中未使用O_NONBLOCK选项。由此看出O_NONBLOCK选项不是阻塞的read/write。他的作用是阻塞open。当以只写方式打开,且没有另外的进程以读的方式打开时,那么这个open就会被阻塞。直到有进程以读操作的方式打开这个FIFO。从运行的表面情况是这样。不知是否正确!希望大侠们多指点!