多進程有名管道通信
負責讀寫的程序
#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;
}
本文章為轉載內容,我們尊重原作者對文章享有的著作權。如有內容錯誤或侵權問題,歡迎原作者聯繫我們進行內容更正或刪除文章。