pipe管道通信

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值