#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char*argv[])
{
int arrfd[2]={0};//文件描述符
int ret = 0;
pid_t cid;//子进程id号
ret=pipe(arrfd);//创建管道
if (ret!=0)
{
printf("create pipe failed\n");
return 1;
}
cid=fork();
if(cid<0)
{
printf("fork failed\n");
close(arrfd[0]);
close(arrfd[1]);
return 2;
}
else if (cid==0)
{
close(arrfd[1]);//fd[1] 写
char buf[64]={0};
while(1)
{
read(arrfd[0],buf,64);
if(strncmp(buf,"exit",4)==0)
{
break;
}
printf("child process :%s",buf);
}
close(arrfd[0]);
}
else
{
char buf[64]={0};
close(arrfd[0]);
while(1)
{
printf("process in parent:\n");
fgets(buf,sizeof(buf),stdin);
if(strncmp(buf,"exit",4)==0)
{
break;
}
write(arrfd[1],buf,sizeof(buf));
}
close(arrfd[1]);
}
return 0;
}