进程间管道通信

管道的阻塞特性

    默认情况下,管道文件是阻塞的,可修改,读取不能偏移
    默认情况下,普通文件是非阻塞的,不可修改,读写可以偏移

管道的分类

1、匿名管道

匿名管道pipe:适用于亲缘关系进程间的,一对一的通信
匿名管道的使用主要用于父子之间
1、同过 pipe[int fd[2]]创建匿名通道的读写功能
2、判断是否创建成功,接收pipe[int fd[2]]返回值如果其值不等于-1则创建成功
3、简单的实现通信,一下是简单示例(函数接口头<unistd.h>)
 

    if(fork()==0)
    {
      //fd[0]是读的权限,
      close(fd[0]);
      char *msg="hello parent";
      write(fd[1],msg,strlen(msg));
    }
    else
    {
     //fd[1]是写的权限
      close(fd[1]);
      //初始化空字符数组
      char buf[50]={0};
      read(fd[0],buf,sizeof(buf));
      printf("子代传回的消息:%s\n",buf);
    }

2、具名管道

        具名管道跟匿名管道相对而言,从外形态上看,具名管道更接近普通文件,可以用open打开、支持read()、write();

管道文件创建必须在Ubuntu或者Linux中的路径下创建,因为外部Windows不支持管道文件(重点)
       具名管道的使用(示例):

1、写的示例
#include <stdio.h>
#include <stdbool.h>
#include <fcntl.h>//用于修改管道读写权限
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>


#define FP "fifo"
int mian(int argc,char const *argv[])
{
//创建匿名管道
	if(access(FP,F_OK))
	{
	int rt =mkfifo(FP,0664);
	if(rt ==-1)
	{
	  perror("mkfifo failed");
	  exit(0);
	}
	}
	int fifo_fd=open(FP,O_WRONLY);//这里是用只写的方式打开,只读(O_RDONLY)、读写(O_RDWR)
	if(fifo_fd==-1)
	{
	perror("open FP failed");
	exit(1);
	}
	char msg[50];
	bzero(msg,sizeof msg);
	fgets(msg,sizeof msg,stdin);
	write(fifo_fd,msg,strlen(msg));
	close(fifo_fd);
    return 0;
}
2、读的示例
#include <stdio.h>
#include <stdbool.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int mian(int argc,char const *argv[])
{
    #define FP "fifo"
	//创建匿名管道
	if(access(FP,F_OK))
	{
	int rt =mkfifo(FP,0664);
	if(rt ==-1)
	{
	  perror("mkfifo failed");
	  exit(0);
	}
	}
	int fifo_fd=open(FP,O_RDONLY);//这里是用只写的方式打开,只写(O_WRONLY)、读写(O_RDWR)
	if(fifo_fd==-1)
	{
	perror("open FP failed");
	exit(1);
	}
	char buf[50];
	bzero(buf,sizeof buf);
	read(fifo_fd,buf,sizeof buf);
	printf("%s\n",buf);
	close(fifo_fd);
    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值