進程間通訊IPC-命名管道FIFO

    FIFO又被稱爲命名管道,未命名的管道只能在兩個相關的進程之間使用,而這兩個相關的進程還要有一個共同建立了它們的祖先進程,可是FIFO,不相關的進程之間也能交換數據。
linux

    FIFO是一種文件類型。經過stat結構的st_mode成員的編碼能夠知道文件是不是FIFO類型,在linux下查看本身建立的FIFO文件:
shell

    

建立FIFO相似於建立文件,也存在於文件系統之中。定義以下:函數

#include <sys/stat.h>
int mkfifo(const char* path, mode_t mode);
int mkfifoat(int fd, const char* path, mode_t mode);

兩個函數返回值:若成功返回0,失敗則返回-1,使用方法參照open函數。編碼

編寫本身的後臺FIFO讀取程序:.net

#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>

int main(int argc, char* argv[])
{
  int fd;
  int nRead;
  char szBuff[128];
  const char* szPath = "/tmp/fifo";         //臨時目錄的一個fifo,能夠在程序裏建立也能夠在shell裏建立

  fd = open(szPath, O_RDONLY, 0);
  if (-1 == fd)
    {
      printf("open fifo error\n");
      goto exit;
    }

  while(1)
    {
      if((nRead = read(fd, szBuff, sizeof(szBuff))) == -1)
        {
          if (errno == EAGAIN)
            printf("no data\n");
        }
      if (szBuff[0] == 'Q')
        break;
      szBuff[nRead] = '\0';
      printf("data:%s\n", szBuff);
      sleep(1);
    }
exit:
  return 0;
}

使用cc fifo.c 編譯成功後獲得a.out,在命令提示符下輸入:code

$ ./a.out &
[1] 4768          //這裏是進程ID回現

將a.out程序做爲一個後臺進程運行。blog

在終端建立fifo(也能夠在程序內建立):進程

$ mkfifo /tmp/fifo
$ ls -ln /tmp/fifo 
prw-rw-r-- 1 1001 1001 0 10月  9 22:04 /tmp/fifo

咱們使用linux自帶的tee回現程序和a.out進行通訊。get

$ tee /tmp/fifo    //標準輸出到fifo
hello fifo!                            //    這裏是我輸入的
hello fifo!                            //    這裏是tee回現功能
data:hello fifo!                    //    這裏是a.out迴應

q
q
data:q                                //    這裏是a.out迴應

Q
Q
hello fifo?
hello fifo?
[1]+  完成                  ./a.out

至此a.out與tee兩個進程之間的通訊已經完成了。it

相關文章
相關標籤/搜索