有名管道:实现无亲缘关系进程间的通信

有名管道的基本概念:

具体操作例程:

vi mkfifo.c   编辑下列代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
  int ret;
  int fd;
  int nread;
  char readbuff[50]={0};
  ret = mkfifo("./myfifo",0755);
  if(ret == -1)
  {
     printf("create mkfifo failed !\n");
     return -1;
  }
  printf("create myfifo success !\n");
  fd = open("./myfifo",O_RDONLY);
  if(fd<0)
  {
     return -1;
  }
  printf("open file success !\n");
  nread = read("fd,readbuff,50"); //readbuff用来存放读取到的从另一个进程的写进有名管道中的内容
  printf("read %d byte from file,content:%s\n",nread,readbuff);
  close(fd);
  return 0;
}

 ps:圈出来的就是生成的管道文件,两无亲缘关系的进程通过此文件进行读写通信,本文中的读进程就是上述的mkfifo.c

另一个进程write.c如下

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main()
{
  int fd;
  char *str="hello world";//将hello world写进通道里
  fd = open("./myfifo",O_WRONLY);
  if(fd<0)
  {
    return -1;
  }
  printf("open file success !\n");
  write(fd,str,strlen(str));
  close(fd);
  return 0;
}

编译两个进程:

gcc mkfifo.c -o read

gcc write.c -o write

在终端中首先运行./read,再打开另一个终端运行./write   得到如下结果

 结果表明:能在read进程中读取到write进程中的内容!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值