Linux进程间通信之有名管道通信

Linux进程间通信之有名管道通信

摘要:因为无名管道的局限性,所以产生了有名管道。

1、什么叫有名管道?(fist in fist out)

首先它是一个文件,文件类型为p,创建方法为 mkfifo log.txt 。进程间通过文件IO 来write()或者read(),来操作管道文件。管道文件不能移动。

2、有名管道的特点

只要能访问管道文件的所有进程之间都可以通过该管道文件通信,严格遵循先进先出。

3、有名管道的创建

//终端:

mkfifo  filename// 

文件内,需要包含库:

#include"sys/types.h"
#include"sys/stat.h"
//使用以下函数创建,创建成功返回0 ,否则返回-1 并置error
int mkfifo(const char *pathname,mode_t mode);
//pathname 是需要创建的管道文件的文件名,mode 是指定管道FIFO 的权限,为三位8进制数
//例如下,创建有名管道文件,规避文件已存在的错误
if((mkfifo(argv[1],0666)<0)&&  errno!=EEXIST)//EEXIST 通过man errno ,在错
{										//误码中表示file exists 文件已存在
	perror("Fail to mkfifo");
	return -1;
}

4、小试牛刀

在这里插入图片描述

write_fifo.c
#include"stdio.h"
#include"string.h"
#include"unistd.h"//
#include <sys/types.h>//下面三行是open的头文件
#include <sys/stat.h>
#include <fcntl.h>

#include"errno.h"

void write_file(int fd)
{
	char buf[100]={0};

	while(1)
	{
		memset(buf,0,sizeof(buf));

		fgets(buf,sizeof(buf),stdin);

		write(fd,buf,strlen(buf));

		if(strncmp(buf,"quit",4)==0)
		{
			break;
		}
	}
	return ;
}

int main(int argc, const char *argv[])
{
	int fd,n;
	if(argc!=2)
	{
		fprintf(stderr,"usage:%s log.txt",argv[0]);
		return -1;
	}

	if((mkfifo(argv[1],0666))&&errno!=EEXIST)
	{
		perror("Fail to mkfifo");
		return -1;
	}

	fd=open(argv[1],O_WRONLY);
	
	if(fd<0)
	{
		perror("Fail to open");
		return -1;
	}
	
	write_file(fd);
	
	close(fd);

	return 0;
}

read_fifo.c
#include"stdio.h"

#include"string.h"

#include"unistd.h"
#include <sys/types.h>//下面三行是open的頭文件
#include <sys/stat.h>
#include <fcntl.h>

#include"errno.h"

void read_file(int fd)
{
	char buf[100]={0};
	int n;
	while(1)
	{
		memset(buf,0,sizeof(buf));

		n=read(fd,buf,sizeof(buf));

		
		if(strncmp(buf,"quit",4)==0)
		{
			break;
		}

		printf("read:%s  bytes:%d\n",buf,n);
	}
	return ;
}

int main(int argc, const char *argv[])
{
	int fd,n;
	if(argc!=2)
	{
		fprintf(stderr,"usage:%s log.txt",argv[0]);
		return -1;
	}

	if((mkfifo(argv[1],0666))&&errno!=EEXIST)
	{
		perror("Fail to mkfifo");
		return -1;
	}

	fd=open(argv[1],O_RDONLY);
	
	if(fd<0)
	{
		perror("Fail to open");
		return -1;
	}
	
	read_file(fd);
	
	close(fd);

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jun8086

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值