博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linux Linux程序练习九
阅读量:7122 次
发布时间:2019-06-28

本文共 2043 字,大约阅读时间需要 6 分钟。

题目:利用多线程与有名管道技术,实现两个进程之间发送即时消息,实现聊天功能
思路:关键在于建立两个有名管道,利用多线程技术,进程A中线程1向管道A写数据,进程B中线程2从管道A读数据,进程A线程2从管道B中读数据,进程B中线程1往管道B中写数据。
//利用多线程与有名管道技术,实现两个进程之间发送即时消息,实现聊天功能//进程A#include 
#include
#include
#include
#include
#include
#include
#include
#include
//从管道1中读数据 void * Threadread(void * arg) { //open the fifo int fd = 0; //open the fifo in read and write mode--以读写方式打开管道 fd = open("/home/test/1/fifo1", O_RDONLY); if (fd == -1) { printf("open the fifo failed ! error message :%s\n", strerror(errno)); return NULL; } char buf[100] = { 0 }; //从管道中读数据 while (read(fd, buf, sizeof(buf)) > 0) { printf("%s", buf); memset(buf, 0, sizeof(buf)); } close(fd); return NULL; } //往管道2中写数据 void * ThreadWrite(void * arg) { //open the fifo int fd = 0; //open the fifo in read and write mode--以读写方式打开管道 fd = open("/home/test/1/fifo2", O_WRONLY); if (fd == -1) { printf("open the fifo failed ! error message :%s\n", strerror(errno)); return NULL; } char buf[100] = { 0 }; while (1) { //往标准输入上读数据 read(STDIN_FILENO, buf, sizeof(buf)); //在管道中写数据 write(fd, buf, strlen(buf)); memset(buf, 0, sizeof(buf)); } close(fd); return NULL; } int main(int arg, char * args[]) { //两线程共用一个文件描述符 pthread_t thr1, thr2; //创建读数据线程 if (pthread_create(&thr1, NULL, Threadread, NULL) != 0) { printf("create thread is failed ! error mesage :%s\n", strerror(errno)); return -1; } //创建写数据线程 if (pthread_create(&thr2, NULL, ThreadWrite, NULL) != 0) { printf("create thread is failed ! error mesage :%s\n", strerror(errno)); return -1; } //等待两线程都返回 关闭文件描述符 pthread_join(thr1, NULL); pthread_join(thr2, NULL); return 0; }
.SUFFIXES:.c .oCC=gccSRCS1=tec01.cSRCS2=tec02.cOBJS1=$(SRCS1:.c=.o)OBJS2=$(SRCS2:.c=.o) EXEC1=a EXEC2=b start:$(OBJS1) $(OBJS2) $(CC) -lpthread -o $(EXEC1) $(OBJS1) $(CC) -lpthread -o $(EXEC2) $(OBJS2) @echo "^_^-----OK------^_^" .c.o: $(CC) -Wall -g -o $@ -c $< clean: rm -f $(OBJS1) rm -f $(OBJS2) rm -f $(EXEC1) rm -f $(EXEC2)

转载地址:http://fkael.baihongyu.com/

你可能感兴趣的文章
Linux-系统时钟
查看>>
LINUX 安装错误笔记ins_ctx.mk
查看>>
Linq实现点击率问题
查看>>
VMware vSphere 5.1 群集深入解析(二十三)- 数据存储架构与设计
查看>>
GitLab: API is not accessibl
查看>>
LVM分区在线扩容
查看>>
OpenSSL介绍
查看>>
Redis 集群部署
查看>>
XenMotion 与HA的区别
查看>>
|深入浅出|数据库范式
查看>>
SAP R3 Oracle 9i ORA-06413 连接未打开错误
查看>>
Liferay 启动过程分析13-初始化Resource Action
查看>>
因为根目录磁盘满了,我移动数据和软件造成mysql启动不了,查原因mysql.sock不在了...
查看>>
Windows 7之BitLock To Go
查看>>
XML的操作——JAXB进行Java对象和XML之间的转换
查看>>
Domino9下通过定时代理—使多台domino 服务器进行数据库复制(同步)
查看>>
VS2008 使用小技巧 提高编程效率
查看>>
安装Operations Manager代理程序
查看>>
修改Outlook脱机文件(.ost)的保存位置
查看>>
FeDex Tracking Message-MVP
查看>>