您的位置:首页 > 运维架构 > Linux

Linux下的有名管道(05)---使用两个管道实现两个进程之间的通信(对讲机模式)

2015-09-21 16:52 961 查看
环境:Vmware Workstation;CentOS-6.4-x86_64

说明:

对讲机模式:一个进程输入完成一句话,必须等待第二个进程输入完成一句话之后才能再次输入。

步骤:

1、创建两个管道:

[negivup@negivup mycode]$ mkfifo fifo1
[negivup@negivup mycode]$ mkfifo fifo2
[negivup@negivup mycode]$ ls
fifo1 fifo22、编写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[])
{
// 以只读的方式打开fifo1,从fifo1中读取数据
int fd1 = open("fifo1", O_RDONLY);
// 判断是否成功打开管道
if (fd1 == -1)
{
printf("Message : %s\n", strerror(errno));
return -1;
}

// 以只写的方式打开fifo2,向fifo2管道中写入数据
int fd2 = open("fifo2", O_WRONLY);
// 判断是否成功打开管道
if (fd1 == -1)
{
printf("Message : %s\n", strerror(errno));
return -1;
}

// 定义文件缓冲区
char buf[1024];

// 循环读取文件
while (1)
{
// 清空缓冲区中的数据
memset(buf, 0, sizeof(buf));
// 从fifo1中读取数据
read(fd1, buf, sizeof(buf));
printf("readfifo : %s", buf);

// 清空缓冲区中的数据
memset(buf, 0, sizeof(buf));
// 向fifo2中写入数据
read(STDIN_FILENO, buf, sizeof(buf));
write(fd2, buf, strlen(buf));
}

// 关闭管道
close(fd1);
close(fd2);

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 <
4000
;unistd.h>

int main(int argc, char *args[])
{
// 以只写的方式打开fifo1,向fifo1管道中写入数据
int fd1 = open("fifo1", O_WRONLY);
// 判断是否成功打开管道
if (fd1 == -1)
{
printf("Message : %s\n", strerror(errno));
return -1;
}

// 以只读的方式打开fifo2,从fifo2中读取数据
int fd2 = open("fifo2", O_RDONLY);
// 判断是否成功打开管道
if (fd1 == -1)
{
printf("Message : %s\n", strerror(errno));
return -1;
}

// 创建文件缓冲区
char buf[1024];
// 循环读写管道中的数据
while (1)
{
// 清空缓冲区中的数据
memset(buf, 0, sizeof(buf));
// 从键盘上读取用户输入
read(STDIN_FILENO, buf, sizeof(buf));
// 将缓冲区的内容写入到管道
write(fd1, buf, strlen(buf));

// 清空缓冲区中的数据
memset(buf, 0, sizeof(buf));
// 从管道中读取数据
read(fd2, buf, sizeof(buf));
printf("writefifo : %s", buf);
}

// 关闭管道
close(fd1);
close(fd2);

return 0;
}5、编译并执行readfifo:

[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
safd
writefifo :
hjk
writefifo : sdf

然后就可以在一个终端中输入一句话,在另一个终端中收到;然后在另一个终端中输入一句话,在第一个终端中可以收到。

这就实现了两个进程之间的通信了。

需要特别注意的是,一个管道的一端,如果确定是读取的操作,那么就不能写入;同理,如果确定是写入的操作,就不能读取。

PS:根据传智播客视频学习整理得出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: