织梦CMS - 轻松建站从此开始!

罗索

Linux pipe函数

落鹤生 发布于 2014-01-15 22:27 点击:次 
1. 函数说明 pipe(建立管道): 1) 头文件 #includeunistd.h 2) 定义函数: int pipe(int filedes[2]); 3) 函数说明: pipe()会建立管道,并将文件描述词由参数filedes数组返回。 filedes[0]为管道里的读取端 filedes[1]则为管道的写入端。 4) 返回值: 若成功则返回
TAG: pipe  管道  

1. 函数说明

pipe(建立管道):
1) 头文件 #include<unistd.h>
2) 定义函数: int pipe(int filedes[2]);
3) 函数说明: pipe()会建立管道,并将文件描述词由参数filedes数组返回。
              filedes[0]为管道里的读取端
              filedes[1]则为管道的写入端。
4) 返回值:  若成功则返回零,否则返回-1,错误原因存于errno中。

    错误代码:
         EMFILE 进程已用完文件描述词最大量
         ENFILE 系统已无文件描述词可用。
         EFAULT 参数 filedes 数组地址不合法。

2. 举例

  1. #include <unistd.h> 
  2. #include <stdio.h> 
  3.  
  4. int main( void ) 
  5.     int filedes[2]; 
  6.     char buf[80]; 
  7.     pid_t pid; 
  8.      
  9.     pipe( filedes ); 
  10.     pid=fork();         
  11.     if (pid > 0) 
  12.     { 
  13.         printf( "This is in the father process,here write a string to the pipe.\n" ); 
  14.         char s[] = "Hello world , this is write by pipe.\n"
  15.         write( filedes[1], s, sizeof(s) ); 
  16.         close( filedes[0] ); 
  17.         close( filedes[1] ); 
  18.     } 
  19.     else if(pid == 0) 
  20.     { 
  21.         printf( "This is in the child process,here read a string from the pipe.\n" ); 
  22.         read( filedes[0], buf, sizeof(buf) ); 
  23.         printf( "%s\n", buf ); 
  24.         close( filedes[0] ); 
  25.         close( filedes[1] ); 
  26.     } 
  27.      
  28.     waitpid( pid, NULL, 0 ); 
  29.      
  30.     return 0; 

运行结果:


[root@localhost src]# gcc pipe.c
[root@localhost src]# ./a.out
This is in the child process,here read a string from the pipe.
This is in the father process,here write a string to the pipe.
Hello world , this is write by pipe.

 

当管道中的数据被读取后,管道为空。一个随后的read()调用将默认的被阻塞,等待某些数据写入。

若需要设置为非阻塞,则可做如下设置:

        fcntl(filedes[0], F_SETFL, O_NONBLOCK);
        fcntl(filedes[1], F_SETFL, O_NONBLOCK);

(myarrow)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201401/16882.html]
本文出处:CSDN博客 作者:myarrow 原文
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容