同一个进程使用pipe(管道)的例子

使用C语言在UNIX中使用pipe(2)系统调用时,这个函数会让系统构建一个匿名管道,这样在进程中就打开了两个新的,打开的文件描述符:一个只读端和一个只写端。管道的两端是两个普通的,匿名的文件描述符,这就让其他进程无法连接该管道。 

gcc pipe.c

./a.out

源代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


#define COUNT (10)
int main(int argc, char *argv[])  
{  
  int pipefd[2];  
  int read_count = 0;
  char buf[COUNT] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};;  
  if (pipe(pipefd) == -1) {  
    perror("call pipe failed \n");  
    exit(EXIT_FAILURE);  
  }  
  printf("write %d chars to pipe1 \n", COUNT);
  write(pipefd[1], buf, COUNT);  


  while (read(pipefd[0], &buf, 1) > 0) 
  {
    printf("read %c from pipe0\n", buf[0]);
    read_count++;
    if(read_count == COUNT)
    {
      printf("total read %d chars \n", read_count);
      break;
    }  
  } 


  close(pipefd[0]);  
  close(pipefd[1]);  
}  

编译及执行结果:

[root@alexs-centos core_dump]# gcc pipe.c 
[root@alexs-centos core_dump]# ./a.out 
write 10 chars to pipe1 
read 0 from pipe0
read 1 from pipe0
read 2 from pipe0
read 3 from pipe0
read 4 from pipe0
read 5 from pipe0
read 6 from pipe0
read 7 from pipe0
read 8 from pipe0
read 9 from pipe0
total read 10 chars 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值