歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux服務器 >> Linux一個命名管道

Linux一個命名管道

日期:2017/3/2 16:33:20   编辑:Linux服務器

今天完成命名管道的實驗。

  命名管道也是按照文件操作流程進行的,可以看做特殊文件。

  寫管道進程:打開-寫-關閉

  讀管道進程:打開-讀-關閉

  本實驗采用阻塞式讀寫管道,一個程序寫,另一個讀。

  源代碼來自華清遠見:

  寫:

  #include<sys/types.h>

  #include<sys/stat.h>

  #include<errno.h>

  #include<fcntl.h>

  #include<stdio.h>

  #include<stdlib.h>

  #include<limits.h>

  #define MYFIFO "/tmp/myfifo"

  #define MAX_BUFFER_SIZE PIPE_BUF

  int main(int argc, char* argv[])

  {

  char buff[MAX_BUFFER_SIZE];

  int fd;

  int nwrite;

  if(argc <= 1)

  {

  printf("usage: ./write string!\n");

  exit(1);

  }

  sscanf(argv[1], "%s", buff);

  fd = open(MYFIFO, O_WRONLY);//打開管道,寫阻塞方式

  if(fd == -1)

  {

  printf("open fifo file error!\n");

  exit(1);

  }

  if((nwrite = write(fd, buff, MAX_BUFFER_SIZE)) > 0)//寫管道

  {

  printf("write '%s' to FIFO!\n ", buff);

  }

  close(fd);//關閉

  exit(0);

  }

  讀:

  #include<sys/types.h>

  #include<sys/stat.h>

  #include<errno.h>

  #include<fcntl.h>

  #include<stdio.h>

  #include<stdlib.h>

  #include<limits.h>

  #define MYFIFO "/tmp/myfifo"

  #define MAX_BUFFER_SIZE PIPE_BUF

  int main()

  {

  char buff[MAX_BUFFER_SIZE];

  int fd;

  int nread;

  //判斷管道是否存在,如果不存在則創建

  if(access(MYFIFO, F_OK) == -1)

  {

  if((mkfifo(MYFIFO, 0666) < 0) && (errno != EEXIST))

  {

  printf("cannot creat fifo file!\n");

  exit(1);

  }

  }

  fd = open(MYFIFO, O_RDONLY);//打開管道,只讀阻塞方式

  if(fd == -1)

  {

  printf("open fifo file error!\n");

  exit(1);

  }

  while(1)

  {

  memset(buff, 0, sizeof(buff));

  if((nread = read(fd, buff, MAX_BUFFER_SIZE)) > 0)//讀管道

  {

  printf("read '%s' from FIFO\n", buff);

  }

  }

  close(fd);//關閉

  exit(0);

  }

  編譯運行,打開兩個終端,一個寫,一個讀。

Copyright © Linux教程網 All Rights Reserved