linux-C管道

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

void read_data(int pipes[]){//从管道读数据
  char c;
  int rc;
  close(pipes[1]);//读进程不用写管道pipes[1]为写管道
  while ((rc=read(pipes[0],&c,1))>0){
     printf("%c",c);
  }
  close(pipes[0]);
  exit(0);
}

void write_data(int pipes[]){//写管道数据
  char c;
  int rc;
  close(pipes[0]);//写进程不用读管道pipes[0]为读管道
  scanf("%c",&c);
  while (c!='x'){//读到x后退出
     rc=write(pipes[1],&c,1);
     scanf("%c",&c);
     if (rc==-1){  //错误
        perror("parent write error");
        close(pipes[1]);
        exit(1);
     }
  }
  close(pipes[1]);
  exit(0);
}

int main(int argc,char *argv[]){
  int pipes[2];
  pid_t pid;
  int rc;

  rc=pipe(pipes);
  if (rc==-1){  
     perror("pipe error");
     exit(1);
  }
  pid=fork();
  if (pid==0) read_data(pipes);
  else write_data(pipes);
  return 0;
}

 knoppix@Microknoppix:/mnt-system/deepfuture$ gcc -o test11 test11.c
test11.c: In function 'read_data':
test11.c:13: warning: incompatible implicit declaration of built-in function 'exit'
test11.c: In function 'write_data':
test11.c:27: warning: incompatible implicit declaration of built-in function 'exit'
test11.c:31: warning: incompatible implicit declaration of built-in function 'exit'
test11.c: In function 'main':
test11.c:42: warning: incompatible implicit declaration of built-in function 'exit'
knoppix@Microknoppix:/mnt-system/deepfuture$ ./test11
q
q
r
r
u
u
k
k
x

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值