Linux进程间通信方式----FIFO

来源:互联网 发布:excel 数组运算 编辑:程序博客网 时间:2024/04/29 15:01

FIFO类似于管道,是一个单向的数据流。不同于管道的是,每个FIFO都有一个路径名与之关联,从而允许无亲缘关系的进程访问同一个FIFO,进行进程间通信。

我按照书上写了一个简单的FIFO通信的例子,主要结构如下:

服务端:

mkfifo(FIFO1, 0777);mkfifo(FIFO2, 0777);open(FIFO1, O_RDONLY, 0);open(FIFO2, O_RWONLY, 0);....


客户端:

open(FIFO2, O_RDONLY, 0);open(FIFO1, O_RWONLY, 0);......

执行的过程中发现服务端阻塞在open(FIFO1, O_RDONLY, 0);,客户端阻塞在open(FIFO2, O_RDONL, 0);

之前使用open的时候没遇到过open阻塞的情况,打开open的man手册发现下面这句话:

O_NONBLOCK

When opening a FIFO with O_RDONLY or O_WRONLY set:

  * If O_NONBLOCK is set, an open() for reading-only shall return without delay. An open() for writing-only shall return an error if no process  currently  has

     the file open for reading.

   * If  O_NONBLOCK  is  clear,  an open() for reading-only shall block the calling thread until a thread opens the file for writing. An open() for writing-only

      shall block the calling thread until a thread opens the file for reading.

原来服务端的open(FIFO1, O_RDONLY, 0)要等到open(FIFO1, O_RWONLY, 0)之后才会返回,

客户端的open(FIFO1, O_RWONLY, 0)要等到open(FIFO1, O_RDONLY, 0)之后返回,这两个进程相互等待造成了死锁。

解决办法:

调换服务端或者客户端中打开FIFO1和FIFO2的顺序,以相同的顺序打开就能避免死锁。