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

本文共 1451 字,大约阅读时间需要 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);

 

转载于:https://www.cnblogs.com/mfrbuaa/p/4589323.html

你可能感兴趣的文章
esp32-智能语音-cli(调试交互命令)
查看>>
netty与MQ使用心得
查看>>
关于dl dt dd 文字过长换行在移动端显示对齐的探讨总结
查看>>
swoolefy PHP的异步、并行、高性能网络通信引擎内置了Http/WebSocket服务器端/客户端...
查看>>
Python学习笔记
查看>>
unshift()与shift()
查看>>
使用 NPOI 、aspose实现execl模板公式计算
查看>>
行为型模式:中介者模式
查看>>
How to Notify Command to evaluate in mvvmlight
查看>>
33. Search in Rotated Sorted Array
查看>>
461. Hamming Distance
查看>>
Python垃圾回收机制详解
查看>>
jquery 编程的最佳实践
查看>>
MeetMe
查看>>
IP报文格式及各字段意义
查看>>
(转载)rabbitmq与springboot的安装与集成
查看>>
C2. Power Transmission (Hard Edition)(线段相交)
查看>>
STM32F0使用LL库实现SHT70通讯
查看>>
Atitit. Xss 漏洞的原理and应用xss木马
查看>>
MySQL源码 数据结构array
查看>>