首页 > 代码库 > 有名管道_2
有名管道_2
编程实现双方通信
a.c
/************************************************************************* > File Name: send.c > Author: KrisChou > Mail:zhoujx0219@163.com > Created Time: Fri 22 Aug 2014 02:46:06 PM CST ************************************************************************/#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdlib.h>#include <string.h>int main(int argc, char* argv[])//EXE send_fifo recv_fifo{ /* A创建管道1,我们假定其先发消息,再收消息 */ /* 管道2由B创建 */ printf("create a fifo_1...\n"); if(-1 == mkfifo(argv[1], 0666)) { perror("mkfifo"); exit(1); } printf("finish make fifo_1 !\n"); /* A以写方式打开管道1,以读方式打开管道2 */ int fd_send, fd_recv ; printf("open fifo....\n"); fd_send = open(argv[1], O_WRONLY); fd_recv = open(argv[2], O_RDONLY); if(fd_send == -1 || fd_recv == -1) { perror("open"); unlink(argv[1]); /* 如果打开管道失败,删除A自己创建的管道1 */ exit(1); } printf("open fifo sucess ! \n"); char send_buf[1024]; char recv_buf[1024]; /* child负责接收消息 */ if(fork() == 0) { close(fd_send); while(memset(recv_buf,0,1024), read(fd_recv, recv_buf , 1024) > 0) { write(1,recv_buf,strlen(recv_buf)); } close(fd_recv); exit(1); } /* parent负责发送消息 */ close(fd_recv); while(memset(send_buf,0,1024), fgets(send_buf,1024,stdin) != NULL) { write(fd_send, send_buf,strlen(send_buf)); } close(fd_send); wait(NULL); printf("A over ! \n"); unlink(argv[1]); //unlink(argv[2]); return 0 ;}
b.c
/************************************************************************* > File Name: send.c > Author: KrisChou > Mail:zhoujx0219@163.com > Created Time: Fri 22 Aug 2014 02:46:06 PM CST ************************************************************************/#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdlib.h>#include <string.h>int main(int argc, char* argv[])//EXE send_fifo recv_fifo{ /* A创建管道1,我们假定其先发消息,再收消息 */ /* 管道2由B创建 */ printf("create a fifo_1...\n"); if(-1 == mkfifo(argv[2], 0666)) { perror("mkfifo"); exit(1); } printf("finish make fifo_1 !\n"); /* A以写方式打开管道1,以读方式打开管道2 */ int fd_send, fd_recv ; printf("open fifo....\n"); fd_recv = open(argv[1], O_RDONLY); fd_send = open(argv[2], O_WRONLY); if(fd_send == -1 || fd_recv == -1) { perror("open"); unlink(argv[2]); /* 如果打开管道失败,删除A自己创建的管道1 */ exit(1); } printf("open fifo sucess ! \n"); char send_buf[1024]; char recv_buf[1024]; /* child负责接收消息 */ if(fork() == 0) { close(fd_send); while(memset(recv_buf,0,1024), read(fd_recv, recv_buf , 1024) > 0) { write(1,recv_buf,strlen(recv_buf)); } close(fd_recv); exit(1); } /* parent负责发送消息 */ close(fd_recv); while(memset(send_buf,0,1024), fgets(send_buf,1024,stdin) != NULL) { write(fd_send, send_buf,strlen(send_buf)); } close(fd_send); wait(NULL); printf("A over ! \n"); unlink(argv[1]); //unlink(argv[2]); return 0 ;}
有名管道_2
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。