linux--管道pipe

来源:互联网 发布:知羽电子相册模板下载 编辑:程序博客网 时间:2024/06/01 20:26
在Linux中,管道是一种使用非常频繁的通信机制。从本质上说,管道也是一种文件,但它又和一般的文件有所不同,管道可以克服使用文件进行通信的两个问题,具体表现为:
  · 限制管道的大小。实际上,管道是一个固定大小的缓冲区。在Linux中,该缓冲区的大小为1页,即4K字节,使得它的大小不象文件那样不加检验地增长。使用单个固定缓冲区也会带来问题,比如在写管道时可能变满,当这种情况发生时,随后对管道的write()调用将默认地被阻塞,等待某些数据被读取,以便腾出足够的空间供write()调用写。
  · 读取进程也可能工作得比写进程快。当所有当前进程数据已被读取时,管道变空。当这种情况发生时,一个随后的read()调用将默认地被阻塞,等待某些数据被写入,这解决了read()调用返回文件结束的问题。

  注意:从管道读数据是一次性操作,数据一旦被读,它就从管道中被抛弃,释放空间以便写更多的数据

#include<stdio.h>

 #include<unistd.h> 

#include<sys/types.h>

 int main(void) 

{

intfd[2],nbytes; pid_tchildpid; 

charstring[]="Hello,world!\n"; 

charreadbuffer[80]; pipe(fd);

 if((childpid=fork())==-1) { perror("fork"); exit(1); } 

if(childpid==0) { /*Child process closes up in put side of pipe*/ close(fd[0]); /*Send"string"through the out put side of pipe*/

 write(fd[1],string,strlen(string)); 

exit(0); }

 else { 

/*Parent process closes up out put side of pipe*/ close(fd[1]); 

/*Readinastringfromthepipe*/ nbytes=read(fd[0],readbuffer,sizeof(readbuffer)); 

printf("Receivedstring:%s",readbuffer); }

 return(0);

 }