需求:
父进程发送一句话给子进程,子进程打印
子进程发送一句话给父进程,父进程打印
代码实现过程:
#include<stdio.h>
#include <unistd.h>
#include <string.h>
int flag=0;
int main(int argc, const char *argv[])
{
int pfd[2]={0};
int pfd1[2]={0};
if(pipe(pfd)<0 || pipe(pfd1)<0){
perror("pipe");
return -1;
}
char str[32] = "";
ssize_t res = 0;
int cnt = 0;
pid_t pid = fork();
if(pid > 0){
while(1){
printf("father says:");
fgets(str,sizeof(str),stdin);
str[strlen(str)-1]='\0';
if((res = write(pfd[1],str,sizeof(str))) < 0){
perror("write");
return -1;
}
bzero(str,sizeof(str));
res = read(pfd1[0],str,sizeof(str));
if(res<0){
perror("read");
return -1;
}
printf("father printf:%s\n",str);
}
}
else if(pid == 0){
while(1){
bzero(str,sizeof(str));
res = read(pfd[0],str,sizeof(str));
if(res<0){
perror("read");
return -1;
}
printf("child printf:%s\n",str);
printf("child says:");
fgets(str,sizeof(str),stdin);
// str[strlen(str-1)]='\0';
if((res = write(pfd1[1],str,sizeof(str))) < 0){
perror("write");
return -1;
}
}
}
else if(pid <0){
perror("fork");
return -1;
}
return 0;
}
代码实现结果: