Linux 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. 举例
#include <unistd.h> #include <stdio.h> 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);
相关文章
- 测试人生 / 这可能是全网Linux 总结得最全的...
- linux inode
- Linux下UTF-8和GB2312互相转换的函数
- 推荐一个快速了解移植uboot以及linux到新板子上的ppt教程
- 认识Linux系统结构
- 学习笔记——Linux下system()函数详解
- 用navicat访问linux数据库,成功实现Navicat访问Linux中安装的MySQL数据库
- 【Linux】手把手教你如何搭建linux环境---云服务器
- Linux中使用expect脚本实现远程机器自动登录_linux shell
- Linux操作系统之exec函数族: execl、execlp、execvp等
- php执行linux命令的6个函数
- 【Linux】linux常用基本命令(转)
- Linux中与网络相关的配置文件
- 【正点原子Linux连载】第二十二章 串口格式化函数移植实验-摘自【正点原子】I.MX6U嵌入式Linux驱动开发指南V1.0
- Linux 之 arm linux 与 windows 使用 tftp 进行文件传输的简单整理
- 【Linux】linux经常使用基本命令
- Linux学习笔记(11)linux网络管理与配置之一——配置路由与默认网关,双网卡绑定(5-6)
- 【Linux】好玩的linux命令
- 每天一个linux命令(46):ping命令