Linux下的有名管道(04)---使用一个管道实现数据的读写

环境:Vmware Workstation;CentOS-6.4-x86_64

说明:

实现的程序,类似于shell操作有名管道。

步骤:

1、创建管道fifo1:

[negivup@negivup mycode]$ mkfifo fifo1
[negivup@negivup mycode]$ ls
fifo1
2、创建并编辑makefile文件:

.SUFFIXES:.c .o

CC=gcc

SRCS1=readfifo.c
OBJS1=$(SRCS1:.c=.o)
EXEC1=readfifo

SRCS2=writefifo.c
OBJS2=$(SRCS2:.c=.o)
EXEC2=writefifo

start: $(OBJS1) $(OBJS2)
	$(CC) -o $(EXEC1) $(OBJS1)
	$(CC) -o $(EXEC2) $(OBJS2)
	@echo "--------------------------OK------------------------"

.c.o:
	$(CC) -Wall -o $@ -c $<

clean:
	rm -rf $(OBJS1) $(EXEC1)
	rm -rf $(OBJS2) $(EXEC2)
3、创建读取管道的源文件readfifo.c:

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

int main(int argc, char *args[])
{
	// 以只读方式打开管道
	int fd = open("fifo1", O_RDONLY);
	// 判断管道是否打开
	if (fd == -1)
	{
		printf("Message : %s\n", strerror(errno));
		return -1;
	}
	
	// 创建缓冲区
	char buf[1024];
	// 清空缓冲区
	memset(buf, 0, sizeof(buf));
	// 拷贝字符串到缓冲区
	strcpy(buf, "hello world");
	// read方法是阻塞的,只有读取到内容才会继续执行
	read(fd, buf, sizeof(buf));
	printf("%s\n", buf);
	// 关闭管道
	close(fd);
	
	return 0;
}
4、创建写入管道的源文件writefifo.c:

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

int main(int argc, char *args[])
{
	// 以只写的方式打开管道
	int fd = open("fifo1", O_WRONLY);
	// 判断管道是否打开
	if (fd == -1)
	{
		printf("Message : %s\n", strerror(errno));
		return -1;
	}
	
	// 创建缓冲区
	char buf[1024];
	// 清空缓冲区
	memset(buf, 0, sizeof(buf));
	// 拷贝字符串到缓冲区
	strcpy(buf, "hello world");
	// 将缓冲区的内容写入到管道中
	write(fd, buf, strlen(buf));
	printf("%s\n", buf);
	// 关闭管道
	close(fd);
	
	return 0;
}
5、编译并执行程序:

[negivup@negivup mycode]$ make
gcc -Wall -o readfifo.o -c readfifo.c
gcc -Wall -o writefifo.o -c writefifo.c
gcc -o readfifo readfifo.o
gcc -o writefifo writefifo.o
--------------------------OK------------------------
[negivup@negivup mycode]$ readfifo 
6、在另一个终端中执行writefifo:

[negivup@negivup mycode]$ writefifo
hello world
7、查看第一个终端的执行效果:

[negivup@negivup mycode]$ readfifo 
hello world


PS:根据传智播客视频学习整理得出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值