linux pipe 写文件,Linux pipe管道函数详解

原标题:Linux pipe管道函数详解

1. 函数说明

pipe(建立管道):

1) 头文件 #include

2) 定义函数: int pipe(int filedes[2]);

3) 函数说明: pipe()会建立管道,并将文件描述词由参数filedes数组返回。

filedes[0]为管道里的读取端

filedes[1]则为管道的写入端。

4) 返回值: 若成功则返回零,否则返回-1,错误原因存于errno中。

错误代码:

EMFILE 进程已用完文件描述词最大量

ENFILE 系统已无文件描述词可用。

EFAULT 参数 filedes 数组地址不合法。

2. 举例

[cpp] view plain copy

1. #include

2. #include

3.

4. int main( void )

5. {

6. int filedes[2];

7. char buf[80];

8. pid_t pid;

9.

10. pipe( filedes );

11. pid=fork();

12. if (pid > 0)

13. {

14. printf( "This is in the father process,here write a string to the pipe.n" );

15. char s[] = "Hello world , this is write by pipe.n";

16. write( filedes[1], s, sizeof(s) );

17. close( filedes[0] );

18. close( filedes[1] );

19. }

20. else if(pid == 0)

21. {

22. printf( "This is in the child process,here read a string from the pipe.n" );

23. read( filedes[0], buf, sizeof(buf) );

24. printf( "%sn", buf );

25. close( filedes[0] );

26. close( filedes[1] );

27. }

28.

29. waitpid( pid, NULL, 0 );

30.

31. return 0;

32. }

运行结果:

[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);返回搜狐,查看更多

责任编辑:

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值