首页 > 服务器 > Linux服务器 > 正文

Linux一个命名管道

2020-05-26 23:49:14
字体:
来源:转载
供稿:网友

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

  写管道进程:打开-写-关闭

  读管道进程:打开-读-关闭

  本实验采用阻塞式读写管道,一个程序写,另一个读。

   写:

  #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);

  }

  编译运行,打开两个终端,一个写,一个读。

 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表