pipe函数是用来创建管道的,当它创建成功会返回两个文件描述符,0是读,1是写;在用管道时,当我们使用读端就要关闭写,使用写端就要关闭读的功能。
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int main()
{
float shu[2]={0.0f};
double shou[2];
int i=0;
int ret;
double re=0.0f;
pid_t pid;
int fd[2];
char str[2][10];
char buff[2][20];
ret=pipe(fd);
if(-1==ret)
{
printf("creat pipe fail!!!\n");
}
pid=fork();
if(-1==pid)
{
printf("creat progress fail!!!\n");
}
else if(0==pid)
{
close(fd[1]);
while(1)
{
i = 0;
while(i<2)
{
read(fd[0],buff[i],20);
i++;
}
for(i=0;i<2;i++)
shou[i]=atof(buff[i]);
re=shou[1]/((shou[0]/100)*(shou[0]/100));
if(re<18)
{
printf("you are too thin!!!\n");
}
if(re>=18&&re<=20)
{
printf("keep your fit!!!\n");
}
if(re>20)
{
printf("you are too fat!!!\n");
}
}
}
else
{
while(1)
{
printf("请输入你的身高xcm,请输入你的体重kg:\n");
for(i=0;i<2;i++)
{
scanf("%f",&shu[i]);
}
while(shu[0]<150||shu[1]>150)
{
printf("请重新输入\n");
for(i=0;i<2;i++)
{
scanf("%f",&shu[i]);
}
}
for(i=0;i<2;i++)
{
sprintf(str[i],"%0.2f",shu[i]);
}
close(fd[0]);
i = 0;
while(i<2)
{
write(fd[1],str[i],strlen(str[i])+1);
sleep(1);
i++;
}
}
}
return 0;
}