使用有名管道完成两个进程之间相互通信
代码:
创建管道:
#include<a.h>
int main(int argc, const char *argv[])
{//创建有名管道文件if(mkfifo("./myfifo1", 0664) != 0){perror("mkfifo1 error");return -1;}printf("myfifo1 create success\n");//创建有名管道文件if(mkfifo("./myfifo2", 0664) != 0){perror("mkfifo2 error");return -1;}printf("myfifo2 create success\n");system("ls -l");//使用getchar阻塞一下getchar();system("rm myfifo1");system("rm myfifo2");return 0;
}
主进程A:
#include<a.h>int main(int argc, const char *argv[])
{pid_t pid = -1; //定义变量存储进程号pid = fork(); //创建一个子进程//后续的程序,父子进程都会执行if(pid > 0){printf("这是父进程对应管道1,pid = %d\n", pid);//以只写的形式打开管道文件int wfd = -1;if((wfd = open("./myfifo1", O_WRONLY)) == -1){perror("open error");return -1;}//向管道文件中循环写入数据char wbuf[128] = "";while(1){bzero(wbuf, sizeof(wbuf)); //清空内容//从终端输入数据printf("管道1请输入>>>>>");fflush(stdout); //刷新行缓冲区read(0, wbuf, sizeof(wbuf));wbuf[strlen(wbuf)-1] = 0; //将回车换成'\0'//将数据写入管道中write(wfd, wbuf, sizeof(wbuf));//判断if(strcmp(wbuf, "quit") == 0){break;}}//关闭文件close(wfd); }else if(pid == 0){printf("这是子进程对应管道2,pid = %d\n", pid);//以只读的形式打开管道文件int rfd = -1;if((rfd = open("./myfifo2", O_RDONLY)) == -1){perror("open error");return -1;}printf("管道2读端打开成功\n");//从管道文件中循环读取数据char rbuf[128] = "";while(1){bzero(rbuf, sizeof(rbuf)); //清空内容//从管道中读取数据read(rfd, rbuf, sizeof(rbuf));printf("收到消息:%s\n", rbuf);//判断if(strcmp(rbuf, "quit") == 0){break;}}//关闭文件close(rfd); }else {perror("fork error");return -1;}while(1);return 0;
}
主进程B:
#include<a.h>int main(int argc, const char *argv[])
{pid_t pid = -1; //定义变量存储进程号pid = fork(); //创建一个子进程//后续的程序,父子进程都会执行if(pid > 0){printf("这是父进程,pid = %d\n", pid);//以只读的形式打开管道文件int rfd = -1;if((rfd = open("./myfifo1", O_RDONLY)) == -1){perror("open error");return -1;}printf("读端打开成功\n");//从管道文件中循环读取数据char rbuf[128] = "";while(1){bzero(rbuf, sizeof(rbuf)); //清空内容//从管道中读取数据read(rfd, rbuf, sizeof(rbuf));printf("收到消息:%s\n", rbuf);//判断if(strcmp(rbuf, "quit") == 0){break;}}//关闭文件close(rfd);}else if(pid == 0){printf("这是子进程,pid = %d\n", pid);//以只写的形式打开管道文件int wfd = -1;if((wfd = open("./myfifo2", O_WRONLY)) == -1){perror("open error");return -1;}printf("写端打开成功\n");//向管道文件中循环写入数据char wbuf[128] = "";while(1){bzero(wbuf, sizeof(wbuf)); //清空内容//从终端输入数据printf("请输入>>>>>");fflush(stdout); //刷新行缓冲区read(0, wbuf, sizeof(wbuf));wbuf[strlen(wbuf)-1] = 0; //将回车换成'\0'//将数据写入管道中write(wfd, wbuf, sizeof(wbuf));//判断if(strcmp(wbuf, "quit") == 0){break;}}//关闭文件close(wfd);}else {perror("fork error");return -1;}printf("hello world\n");while(1);return 0;
}
运行效果: