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文件权限之-i(不可修改权限),a(只可追加权限)
- Linux 等待进程结束 wait() 和 waitpid()
- linux时间
- linux 如何截取一段时间内log日志
- 在linux下 用p7zip 命令行下 解压 iso文件
- Linux系统调优详解(十一)——IO调优之文件打开数目限制
- Atitit.linux 内核 新特性 新功能
- 【华为OD机试 2023最新 】 Linux发行版的数量(C++ 100%)
- linux下mysql 启动命令
- Linux pipe功能
- Linux系统shell脚本基础之function功能
- Linux下利用iverilog进行功能仿真,利用gtkwave查看仿真输出波形
- 嵌入式linux开发,iconv库的移植,libiconv交叉编译
- 嵌入式linux开发,启用域名解析功能
- Linux驱动---休眠与唤醒
- linux下一个C语言flock功能使用 .
- Visual Studio新功能:针对Linux平台的新版SSH终端
- linux安装sz && rz功能
- Linux 系统适用范围
- Linux趣味小知识---tty终端内置的极简QQ功能
- 嵌入式linux开发,启用用户登录功能
- 嵌入式linux开发,启用域名解析功能