首页服务器Linux服务器 Linux一个命名管道

Linux一个命名管道

   命名管道也是按照文件操作流程进行的,可以看做特殊文件。  写管道进程:打开-写-关闭  读管道进程:打开-读-关闭  本实验采用阻塞式读写管道,一个程序写,另一个读。 …

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

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

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

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

   写:

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #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

  #include

  #include

  #include

  #include

  #include

  #include

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

  }

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

 

本文来自网络,不代表1号站长-站长学院|资讯交流平台立场。转载请注明出处: https://www.1cn.cc/fwq/Linux/8096.html
上一篇红帽Linux下的影子工具
下一篇 Linux命令行下登录ssl加密的ftp
admin

作者: admin

这里可以再内容模板定义一些文字和说明,也可以调用对应作者的简介!或者做一些网站的描述之类的文字或者HTML!

为您推荐

评论列表()

    联系我们

    联系我们

    0898-88888888

    在线咨询: QQ交谈

    邮箱: email@wangzhan.com

    工作时间:周一至周五,9:00-17:30,节假日休息

    关注微信
    微信扫一扫关注我们

    微信扫一扫关注我们

    关注微博
    返回顶部