Linux Linux程序练习九
2016-09-11 20:00
225 查看
题目:利用多线程与有名管道技术,实现两个进程之间发送即时消息,实现聊天功能
思路:关键在于建立两个有名管道,利用多线程技术,进程A中线程1向管道A写数据,进程B中线程2从管道A读数据,进程A线程2从管道B中读数据,进程B中线程1往管道B中写数据。
//利用多线程与有名管道技术,实现两个进程之间发送即时消息,实现聊天功能 //进程A #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <pthread.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> //从管道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 .o CC=gcc SRCS1=tec01.c SRCS2=tec02.c OBJS1=$(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)
相关文章推荐
- 随手写了一个linux服务端与window客户端的epoll程序,当做练习把。
- linux后台服务程序练习开发
- Linux练习(处理程序命令行参数)
- Linux_C练习:编写一个程序,求出满足下列条件的四位数:该数是个完全平方数,且第一、三位数字之和为10,第二、四位数字之积为12;
- Linux_C练习:设计一个洗牌发牌的程序;(随机产生52个不同的数)
- linux 每日一练习:父程序与子程序的概念
- Linux Linux程序练习十三(信号阻塞,捕获)
- Linux Linux程序练习十(网络编程大文件发送)
- linux的基本命令及vim程序编辑器的练习
- linux 练习五 如何生成库.so及被C和C++程序可用
- 随手写了一个linux服务端与window客户端的epoll程序,当做练习把。
- Linux Linux程序练习八
- Linux Linux程序练习十五(进程间的通信共享内存版)
- Linux C程序练习(4)进程通信之信号量、共享内存
- Linux Linux程序练习六
- Linux Linux程序练习十八
- 有时间练习下linux下的queue.h这个程序
- Linux Linux程序练习四
- Linux C程序练习(3)进程通信之pipe、fifo、消息队列
- Linux Linux程序练习十四(多进程压力测试)