命名管道(FIFO)

代码:


client.c

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

#define  __PATH__ "/home/chen/7Month/7_28/FIFO/my_fifo"//这个就是管道的名字,和建立的路径

int main()
{
	int fd = open(__PATH__,O_WRONLY,0);//以只写的方式打开
	if(fd < 0){
		perror("error");
		return 2;
	}
	char buf[1024];
	while(1){
		printf("client Enter :");
		fflush(stdout);
		memset(buf,'\0',sizeof(buf));
		fgets(buf,sizeof(buf)-1,stdin);
		buf[strlen(buf)-1] = '\0';
		write(fd,buf,strlen(buf));
		if(strcasecmp(buf,"Quit") == 0){//忽略大小写
			break;
		}
	}
	close(fd);
	printf("client Quit\n");
	return 0;
}

server.c:

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

#define  __PATH__ "/home/chen/7Month/7_28/FIFO/my_fifo"

int main()
{
	if(mkfifo(__PATH__,0666|S_IFIFO) < 0){
		perror("error");
		return 1;
	}
	int fd = open(__PATH__,O_RDONLY,0);//以只读的方式打开命名管道
	printf("open file success\n");
	if(fd < 0){
		perror("error");
	}
	char buf[1024];
	while(1){
		memset(buf,'\0',sizeof(buf));
		int len = read(fd,buf,sizeof(buf)-1);
		if(len > 0){
			printf("client say : %s\n",buf);
		}
		if(strcasecmp("Quit",buf) == 0){//忽略大小写的quit
			break;
		}
	}
	close(fd);
	printf("server Quit\n");
	return 0;
}


运行结果

client.c


server.c


分析:

管道其实就是个文件,生命周期是和普通的文件是一样的,不删除它永远存在



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值