当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
linux认证辅导:命名管道
发布时间:2010/7/12 11:19:54 来源:城市学习网 编辑:ziteng
  今天完成命名管道的实验。
  命名管道也是按照文件操作流程进行的,可以看做特殊文件。
  写管道进程:打开-写-关闭
  读管道进程:打开-读-关闭
  本实验采用阻塞式读写管道,一个程序写,另一个读。
  源代码来自华清远见:
  写:
  #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 [NextPage]   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);
  }
  编译运行,打开两个终端,一个写,一个读。
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved