进程通信--命名管道(FIFO)

一.命名管道(FIFO)

    FIFO不同于管道之处在于它提供一 个路径名与之关联,以FIFO的文件形式存储于文件系统中。命名管道是一个设备文件,因 此,即使进程与创建FIFO的进程不存在亲缘关系,只要可以访问该路径,就能够通过FIFO 相互通信。值得注意的是,FIFO(first input first output)总是按照先进先出的原则工作,第一 个被写入的数据将首先从管道中读出。 

二.命名管道的创建

  int mkfifo(const char *path,mode_t mode); 

  int mknod(const char *path,mode_t mod,dev_t dev); 

    函数mknod参数中path为创建的命名管道的全路径名:mod为创建的命名管道的模式,指明其存取权限;dev为设备值,该值取决于文件创建的种类,它只在创建设备文件时才会用到。这两个函数调用成功都返回0,失败都返回-1。

三.测试用例

 1.头文件

#pragma once

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

#define _FIFO_NAME_ "./my_fifo"
#define _SIZE_ 1024

  2:server端

#include"comm.h"

int main()
{
	if(mkfifo(_FIFO_NAME_,S_IFIFO | 0666) < 0)
	{
		printf("errno:%d,strerror:%s\n",errno,strerror(errno));
	}

	int fd = open(_FIFO_NAME_,O_RDONLY);
	if(fd < 0)
	{
		printf("%s\n",strerror(errno));
		return 2;
	}

	char buf[_SIZE_];
	while(1)
	{
		memset(buf,'\0',sizeof(buf));
		read(fd,buf,sizeof(buf) - 1);
		printf("client# %s\n",buf);
	}

	close(fd);
	return 0;
}
  3.client端

#include"comm.h"

int main()
{
	int fd = open(_FIFO_NAME_,O_WRONLY);
	if(fd < 0)
	{
		printf("%s\n",strerror(errno));
	}

	char buf[_SIZE_];
	while(1)
	{
		printf("Please enter# :");
		memset(buf,'\0',sizeof(buf));
		ssize_t _s = read(1, buf, sizeof(buf) - 1);
		if(_s > 0)
		{
			buf[_s - 1] = '\0';
		}

		write(fd,buf,strlen(buf));
	}
	return 0;
}
四.测试结果



        以上就是本人在学习过程中的一些经验总结。当然,本人能力有限,难免会有纰漏,希望大家可以指正。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值