博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linux pipe函数
阅读量:7012 次
发布时间:2019-06-28

本文共 1401 字,大约阅读时间需要 4 分钟。

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. 举例

#include 
#include
int main( void ){ int filedes[2]; char buf[80]; pid_t pid; pipe( filedes ); pid=fork(); if (pid > 0) { printf( "This is in the father process,here write a string to the pipe.\n" ); char s[] = "Hello world , this is write by pipe.\n"; write( filedes[1], s, sizeof(s) ); close( filedes[0] ); close( filedes[1] ); } else if(pid == 0) { printf( "This is in the child process,here read a string from the pipe.\n" ); read( filedes[0], buf, sizeof(buf) ); printf( "%s\n", buf ); close( filedes[0] ); close( filedes[1] ); } waitpid( pid, NULL, 0 ); 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);

 

转载地址:http://mnqtl.baihongyu.com/

你可能感兴趣的文章
tomcat安全防护之普通用户运行
查看>>
分布式锁与实现(一)——基于Redis实现
查看>>
python学习 dict set 的用法(四)
查看>>
双机热备份的切换时间是这么确定的
查看>>
ADSL拨号上网,拨完了获得的地址IP跟网关一样!
查看>>
Socket.IO连接异常时的内置事件流程图
查看>>
算法学习笔记(四)---第k个二进制数字问题
查看>>
忘记sa密码,又删除了windows身份验证账号的解决方法
查看>>
Open-Falcon 监控系统监控 MySQL/Redis/MongoDB 状态监控
查看>>
1-4 Zabbix 用户管理
查看>>
Visual Studio 2017强制更新方法
查看>>
蓝牙设备探测工具blueranger
查看>>
我的友情链接
查看>>
KaliLinux常用服务配置教程DHCP服务工作流程
查看>>
js基础--javascript基础概念之数组
查看>>
date 输出格式
查看>>
Android控件TextView的实现原理分析
查看>>
java中异常的处理
查看>>
我的友情链接
查看>>
最小生成树算法——Prim和Kruskal算法的实现
查看>>