多进程有名管道通信
负责读写的程序
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main(){
//2.创建子进程
pid_t id=fork();
if(id<0) exit(0);
if(id>0){
//3.父进程负责写数据(只写的方式打开管道1)
printf("我是B父进程, pid:%d\n",getpid());
int fdw = open("fifo2",O_WRONLY); //只写<sys/types.h> <sys/stat.h> <fcntl.h>
if(fdw==-1){ //文件打开失败
perror("open");
exit(0);
}
printf("B打开管道fifo2成功,等待写入...\n");
//开始写入数据
char buf[128];
while (1){
memset(buf, 0, 128);
//获取标准输入的数据
fgets(buf,128,stdin);
//写入数据
int ret=write(fdw,buf,strlen(buf));
if(ret==-1){ //写入错误
perror("write");
exit(0);
}
}
wait(NULL);
}else if(id==0){
//4.子进程负责读数据(只读的方式打开管道2)
printf("我是B子进程, pid:%d\n",getpid());
int fdr = open("fifo1",O_RDONLY); //只写<sys/types.h> <sys/stat.h> <fcntl.h>
if(fdr==-1){ //文件打开失败
perror("open");
exit(0);
}
printf("B打开管道fifo1成功,等待读取数据...\n");
//开始读取数据
char buf[128];
while (1){
memset(buf, 0, 128);
//读取数据
int ret=read(fdr,buf,128);
if(ret==0){ //写入错误
printf("fifo1写段关闭");
exit(0);
}else if(ret < 0) {
perror("read");
break;
}
printf("我是B进程的儿子,从fifo1得到的数据是:%s\n",buf);
}
}
return 0;
}
负责写读的程序
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main(){
//1.创建两个管道
int ret1=access("fifo1",F_OK); //<unistd.h>The value of amode is (R_OK, W_OK, X_OK) or the existence test (F_OK).
int ret2=access("fifo2",F_OK);
if(ret1 ==-1){
printf("创建管道1\n");
ret1 = mkfifo("fifo1",0664); //<sys/types.h> <sys/stat.h>
if(ret1 ==-1){ //创建失败的情况退出
perror("mkfifo");
exit(0); //<unistd.h>
}
}
if(ret2 ==-1){
printf("创建管道2\n");
ret2 = mkfifo("fifo2",0664); //<sys/types.h> <sys/stat.h>
if(ret2 ==-1){ //创建失败的情况退出
perror("mkfifo");
exit(0); //<unistd.h>
}
}
//2.创建子进程
pid_t id=fork();
if(id<0) exit(0);
if(id>0){
//3.父进程负责写数据(只写的方式打开管道1)
printf("我是A父进程, pid:%d\n",getpid());
int fdw = open("fifo1",O_WRONLY); //只写<sys/types.h> <sys/stat.h> <fcntl.h>
if(fdw==-1){ //文件打开失败
perror("open");
exit(0);
}
printf("A打开管道fifo1成功,等待写入...\n");
//开始写入数据
char buf[128];
while (1){
memset(buf, 0, 128);
//获取标准输入的数据
fgets(buf,128,stdin);
//写入数据
int ret=write(fdw,buf,strlen(buf));
if(ret==-1){ //写入错误
perror("write");
exit(0);
}
}
wait(NULL);
}else if(id==0){
//4.子进程负责读数据(只读的方式打开管道2)
printf("我是A子进程, pid:%d\n",getpid());
int fdr = open("fifo2",O_RDONLY); //只写<sys/types.h> <sys/stat.h> <fcntl.h>
if(fdr==-1){ //文件打开失败
perror("open");
exit(0);
}
printf("A打开管道fifo2成功,等待读取数据...\n");
//开始读取数据
char buf[128];
while (1){
memset(buf, 0, 128);
//读取数据
int ret=read(fdr,buf,128);
if(ret==0){ //写入错误
printf("fifo2写段关闭");
exit(0);
}else if(ret < 0) {
perror("read");
break;
}
printf("我是A进程的儿子,从fifo2得到的数据是:%s\n",buf);
}
}
return 0;
}