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

来源:互联网 发布:centos 安装chrome 编辑:程序博客网 时间:2024/05/01 05:47

使用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