作业需求:
要求实现父子进程对话
1.父进程先发送一句话给子进程,子进程接收后打印
2.子进程再回复一句话给父进程,父进程接收后打印3.重复1.2步骤,
当收到quit后,要结束父子进程
实现过程:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
int pfd[2]={0};
int pfd1[2]={0};
char str[20]="";
char str1[20]="";
char str2[20]="quit";
int i=0;
pid_t ws;
ssize_t res,res1;
if(pipe(pfd)<0)
{
perror("pipe");
return -1;
}
if(pipe(pfd1)<0)
{
perror("pipe2");
return -1;
}
pid_t pid=fork();
if(pid>0)
{
while(1)
{
fgets(str,sizeof(str),stdin);
str[strlen(str)-1]='\0';
if(strcmp(str,str2)==0)
break;
write(pfd[1],str,sizeof(str));
bzero(str,sizeof(str));
read(pfd1[0],str,sizeof(str));
printf("this is other %s\n",str);
}
}
if(pid==0)
{
while(1)
{
bzero(str,sizeof(str));
read(pfd[0],str,sizeof(str));
printf("this is main %s\n",str);
fgets(str,sizeof(str),stdin);
str[strlen(str)-1]='\0';
if(strcmp(str,str2)==0)
break;
write(pfd1[1],str,sizeof(str));
}
}
return 0;
}
实现结果:
ubuntu@ubuntu:07_day$ gcc ptf.c -pthread
ubuntu@ubuntu:07_day$ ./a.out
1
this is main 1
2
this is other 2
3
this is main 3
4
this is other 4
5
this is main 5
6
this is other 6
7
this is main 7
8
this is other 8
quit
ubuntu@ubuntu:07_day$