linux 有名管道FIFO的一点理解

        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。从运行的表面情况是这样。不知是否正确!希望大侠们多指点!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值