UNIX环境高级编程——管道读写规则和pipe Capacity、PIPE_BUF
一、当没有数据可读时
O_NONBLOCK disable:read调用阻塞,即进程暂停执行,一直等到有数据来到为止。
O_NONBLOCK enable:read调用返回-1,errno值为EAGAIN。
示例程序如下:
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<signal.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0) int main(int argc, char *argv[])
{
int pipefd[2];
if (pipe(pipefd) == -1)
ERR_EXIT("pipe error"); pid_t pid;
pid = fork();
if (pid == -1)
ERR_EXIT("fork error"); if (pid == 0)
{
sleep(3);
close(pipefd[0]);
write(pipefd[1], "hello", 5);
close(pipefd[1]);
exit(EXIT_SUCCESS);
}
// sleep(3);
close(pipefd[1]);
char buf[10] = {0};
int flags = fcntl(pipefd[0], F_GETFL);
fcntl(pipefd[0], F_SETFL, flags | O_NONBLOCK); //enable fd的O_NONBLOCK
int ret = read(pipefd[0], buf, 10); //默认是disable fd的O_NONBLOCK
if (ret == -1) // 父进程不会阻塞,出错返回
ERR_EXIT("read error");
printf("buf=%s\n", buf); return 0;
}
特意在子进程中sleep了3s,让父进程先被调度运行,而且读端文件描述符标志设置为非阻塞,即立刻出错返回,如下:
huangcheng@ubuntu:~$ ./a.out
read error: Resource temporarily unavailable
假设开启35行,注释29行,让父进程先sleep,子进程先运行,则运行结果:
huangcheng@ubuntu:~$ ./a.out
buf=hello
二、当管道满的时候
O_NONBLOCK disable: write调用阻塞,直到有进程读走数据
O_NONBLOCK enable:调用返回-1,errno值为EAGAIN
管道是一块内存缓冲区,可以写个小程序测试一下管道的容量Pipe Capacity:
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<signal.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0) int main(int argc, char *argv[])
{
int pipefd[2];
if (pipe(pipefd) == -1)
ERR_EXIT("pipe error"); int ret;
int count = 0;
int flags = fcntl(pipefd[1], F_GETFL);
fcntl(pipefd[1], F_SETFL, flags | O_NONBLOCK); // 设置为非阻塞
while (1)
{
ret = write(pipefd[1], "A", 1);
if (ret == -1)
{
printf("err=%s\n", strerror(errno));
break;
} count++;
}
printf("count=%d\n", count); //管道容量 return 0;
}
程序中将写端文件描述符标志设置为非阻塞,当管道被写满时不会等待其他进程读取数据,而是直接返回-1并置errno,输出如下:
huangcheng@ubuntu:~$ ./a.out
err=Resource temporarily unavailable
count=65536
打印了错误码,可以看到管道的容量是64kB,man 7 pipe中也有提到在2.6.11内核以前是4096,现在是65536。
三、如果所有管道读端对应的文件描述符被关闭(管道读端的引用计数等于0),则write操作会产生SIGPIPE信号,默认终止当前进程
示例代码如下:
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<signal.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0) void handler(int sig)
{
printf("recv sig=%d\n", sig);
} int main(int argc, char *argv[])
{
signal(SIGPIPE, handler); int pipefd[2];
if (pipe(pipefd) == -1)
ERR_EXIT("pipe error"); pid_t pid;
pid = fork();
if (pid == -1)
ERR_EXIT("fork error"); if (pid == 0)
{
close(pipefd[0]);
exit(EXIT_SUCCESS);
}
close(pipefd[0]);
sleep(1);
int ret = write(pipefd[1], "hello", 5);
if (ret == -1)
{
printf("err=%s\n", strerror(errno));
} return 0;
}
输出测试:
huangcheng@ubuntu:~$ ./a.out
recv sig=13
err=Broken pipe
父进程睡眠1s确保所有读端文件描述符都已经关闭,如果没有安装SIGPIPE信号的处理函数,则默认终止当前进程,即write函数不会返回,现在write错误返回-1,并置errno=EPIPE,对应的出错信息是Broken pipe。
四、如果所有管道写端对应的文件描述符被关闭(管道写端的引用计数等于0),那么管道中剩余的数据都被读取后,再次read会返回0
示例程序如下:
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<signal.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0) void handler(int sig)
{
printf("recv sig=%d\n", sig);
} int main(int argc, char *argv[])
{
signal(SIGPIPE, handler); int pipefd[2];
if (pipe(pipefd) == -1)
ERR_EXIT("pipe error"); pid_t pid;
pid = fork();
if (pid == -1)
ERR_EXIT("fork error"); if (pid == 0)
{
close(pipefd[1]);
exit(EXIT_SUCCESS);
} close(pipefd[1]);
sleep(1);
char buf[10] = {0};
int ret = read(pipefd[0], buf, 10);
printf("ret = %d\n", ret); return 0;
}
输出测试如下:
huangcheng@ubuntu:~$ ./a.out
ret = 0
同样地父进程睡眠1s确保所有的写端文件描述符都已经关闭,read返回0。
五、当要写入的数据量不大于PIPE_BUF时,linux将保证写入的原子性;当要写入的数据量大于PIPE_BUF时,linux将不再保证写入的原子性。
On Linux, PIPE_BUF is 4096 bytes。
The precise semantics depend on whether the file descriptor is nonblocking (O_NONBLOCK), whether there are multiple writers to the pipe, and on n, the number of bytes to be written。即由文件描述符的标志,是否有多个进程向管道写入以及写入的字节数所决定准确的语义,总共分4种情况,具体可man一下。
下面的程序演示 O_NONBLOCK disabled ,size > PIPE_BUF(4K)的情况 :
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<signal.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0) #define TEST_SIZE 68*1024 // 68KB
/* 默认O_NONBLOCK disabled ,这里验证 size > PIPE_BUF(4K)的情况 */
int main(int argc, char *argv[])
{
char a[TEST_SIZE];
char b[TEST_SIZE]; memset(a, 'A', sizeof(a));
memset(b, 'B', sizeof(b)); int pipefd[2];
int ret = pipe(pipefd);
if (ret == -1)
ERR_EXIT("pipe error"); int pid = fork();
if (pid == 0)
{ close(pipefd[0]);
ret = write(pipefd[1], a, sizeof(a)); // 全部写完才返回
printf("apid=%d write %d bytes to pipe\n", getpid(), ret);
exit(0);
} pid = fork(); if (pid == 0)
{ close(pipefd[0]);
ret = write(pipefd[1], b, sizeof(b));
printf("bpid=%d write %d bytes to pipe\n", getpid(), ret);
exit(0);
} close(pipefd[1]); sleep(1); int fd = open("test.txt", O_WRONLY | O_CREAT | O_TRUNC, 0664);
char buf[1024 * 4] = {0};
int n = 1;
while (1)
{
ret = read(pipefd[0], buf, sizeof(buf)); //当管道被写入数据,就已经可以开始读了,每次读取4k
if (ret == 0) // 管道写端全部关闭,即读到了结尾
break;
printf("n=%02d pid=%d read %d bytes from pipe buf[4095]=%c\n",
n++, getpid(), ret, buf[4095]);
write(fd, buf, ret);
} return 0;
}
输出测试如下:
huangcheng@ubuntu:~$ ./a.out
n=01 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=02 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=03 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=04 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=05 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=06 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=07 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=08 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=09 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=10 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=11 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=12 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=13 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=14 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=15 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=16 pid=2598 read 4096 bytes from pipe buf[4095]=B
bpid=2600 write 69632 bytes to pipe
n=17 pid=2598 read 4096 bytes from pipe buf[4095]=B
n=18 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=19 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=20 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=21 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=22 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=23 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=24 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=25 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=26 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=27 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=28 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=29 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=30 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=31 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=32 pid=2598 read 4096 bytes from pipe buf[4095]=A
n=33 pid=2598 read 4096 bytes from pipe buf[4095]=A
apid=2599 write 69632 bytes to pipe
n=34 pid=2598 read 4096 bytes from pipe buf[4095]=A
分析一下:现在的情况是有两个子进程在对管道进行阻塞写入各68k,即每个子进程完全写入68k才返回,而父进程对管道进行阻塞读取,每次读取4k,打印每4k中的最后一个字符,如果没有数据到达就阻塞等待,如果管道剩余数据不足4k,read 很可能返回 < 4k,但因为我们写入68k是4k整数倍,故不存在这种情况。需要注意的是是边写边读,因为前面说过管道的容量只有64k,当管道被写满时子进程就阻塞等待父进程读取后再写入。由上面输出可以看出B进程先写入64k的B,然后写入剩下的4k的B,接着A进程先写入64k的A之后接着写完最后的4k的A,然后write返回。由A进程write完毕输出的提示可知此时A进程已经写完成了,但父进程还没读取A完毕,当两个子进程全部写完退出时关闭写端文件描述符,则父进程read就会返回0,退出while循环。可以得出结论:当多个进程对管道进行写入,且一次性写入数据量大于PIPE_BUF时,则不能保证写入的原子性,即可能数据是穿插着的。man 手册的解释如下:
O_NONBLOCK disabled, n > PIPE_BUF
The write is nonatomic: the data given to write(2) may be interleaved with write(2)s by other process; the write(2) blocks until n bytes have been written.
注意我们这里设定了size=68k,则写端不能设置成非阻塞,因为PIPE_BUF只有4k,不能一次性写入68k,如果此时管道是满的(64k),则只能返回-1并置错误码为EAGAIN,且一个字符也不写入,若不是满的,则写入的字节数是不确定的,需要检查write的返回值,而且这些字节很可能也与其他进程写入的数据穿插着。读端也不能设置为非阻塞,如果此时尚未有数据写入(管道为空)则返回-1并置错误码为EAGAIN,如果有部分数据已经写入,则读取的数据字节数也是不确定的,需要检查read的返回值。总之测试4种不同情形下的情况也应设置不同的条件。
详细说明见:《UNIX环境高级编程——管道和FIFO的额外属性》
O_NONBLOCK disabled, n <= PIPE_BUF
All n bytes are written atomically; write(2) may block if there is not room for n
bytes to be written immediately O_NONBLOCK enabled, n <= PIPE_BUF
If there is room to write n bytes to the pipe, then write(2) succeeds immediately,
writing all n bytes; otherwise write(2) fails, with errno set to EAGAIN. O_NONBLOCK disabled, n > PIPE_BUF
The write is non-atomic: the data given to write(2) may be interleaved with
write(2)s by other process; the write(2) blocks until n bytes have been written. O_NONBLOCK enabled, n > PIPE_BUF
If the pipe is full, then write(2) fails, with errno set to EAGAIN. Otherwise, from
1 to n bytes may be written (i.e., a "partial write" may occur; the caller should
check the return value from write(2) to see how many bytes were actually written),
and these bytes may be interleaved with writes by other processes.
管道的前4种读写规则具有普遍意义,Tcp socket 也具有管道的这些特性。
UNIX环境高级编程——管道读写规则和pipe Capacity、PIPE_BUF的更多相关文章
- 管道读写规则和Pipe Capacity、PIPE_BUF
一.当没有数据可读时 O_NONBLOCK disable:read调用阻塞,即进程暂停执行,一直等到有数据来到为止. O_NONBLOCK enable:read调用返回-1,errno值为EAGA ...
- UNIX环境高级编程——管道和FIFO的额外属性
一个描述符能以两种方式设置成非阻塞. (1)调用open时可以指定O_NONBLOCK标志. writefd = open(FIFO1,O_WRONLY | O_NONBLOCK,0); (2)如果一 ...
- UNIX环境高级编程——管道和FIFO限制
系统加于管道和FIFO的唯一限制为: OPEN_MAX 一个进程在任意时刻打开的最大描述符数: PIPE_BUF 可原子的写往一个管道或FIFO的最大数据量. OPEN_MAX的值 ...
- (九) 一起学 Unix 环境高级编程 (APUE) 之 线程
. . . . . 目录 (一) 一起学 Unix 环境高级编程 (APUE) 之 标准IO (二) 一起学 Unix 环境高级编程 (APUE) 之 文件 IO (三) 一起学 Unix 环境高级编 ...
- (十二) 一起学 Unix 环境高级编程 (APUE) 之 进程间通信(IPC)
. . . . . 目录 (一) 一起学 Unix 环境高级编程 (APUE) 之 标准IO (二) 一起学 Unix 环境高级编程 (APUE) 之 文件 IO (三) 一起学 Unix 环境高级编 ...
- (一) 一起学 Unix 环境高级编程 (APUE) 之 标准IO
. . . . . 目录 (一) 一起学 Unix 环境高级编程 (APUE) 之 标准IO (二) 一起学 Unix 环境高级编程 (APUE) 之 文件 IO (三) 一起学 Unix 环境高级编 ...
- (五) 一起学 Unix 环境高级编程 (APUE) 之 进程环境
. . . . . 目录 (一) 一起学 Unix 环境高级编程 (APUE) 之 标准IO (二) 一起学 Unix 环境高级编程 (APUE) 之 文件 IO (三) 一起学 Unix 环境高级编 ...
- (七) 一起学 Unix 环境高级编程(APUE) 之 进程关系 和 守护进程
. . . . . 目录 (一) 一起学 Unix 环境高级编程 (APUE) 之 标准IO (二) 一起学 Unix 环境高级编程 (APUE) 之 文件 IO (三) 一起学 Unix 环境高级编 ...
- 【UNIX环境高级编程】文件I/O
[UNIX环境高级编程]文件I/O大多数文件I/O只需要5个函数: open.read.write.lseek以及close 不带缓冲的I/O: 每个read和write都调用内核中的一个系统调用 1 ...
随机推荐
- SynchronizedMap和ConcurrentHashMap的深入分析
http://blog.sina.com.cn/s/blog_5157093c0100hm3y.html java5中新增了ConcurrentMap接口和它的一个实现类ConcurrentHashM ...
- struct2 拿到url的方法
在Action中: HttpServletRequest request = ServletActionContext.getRequest(); String url =request.getReq ...
- PHP 常用函数集合
PHP is_numeric() 函数 由 陈 创建, 最后一次修改 2016-12-02 定义和用法 is_numeric() - 检测变量是否为数字或数字字符串 语法 bool is_numeri ...
- ABP文档笔记 - 规约
ABP框架 - 规约 简介 规约模式是一个特别的软件设计模式,业务逻辑可以使用boolean逻辑重新链接业务逻辑(维基百科). 实践中的大部分情况,它是为实体或其它业务对象,定义可复用的过滤器. 理解 ...
- CNN在中文文本分类的应用
深度学习近一段时间以来在图像处理和NLP任务上都取得了不俗的成绩.通常,图像处理的任务是借助CNN来完成的,其特有的卷积.池化结构能够提取图像中各种不同程度的纹理.结构,并最终结合全连接网络实现信息的 ...
- [BBS]搭建开源论坛之JForum安装使用札记
本文作者:sushengmiyan 本文地址:http://blog.csdn.net/sushengmiyan/article/details/47761303 目录 目录 BBS搭建开源论坛之JF ...
- Dynamics CRM 导出系统中实体的属性字段到EXCEL
我们在CRM中看元数据信息,可以通过SDK中的metadata browser的解决方案包,但该解决方案包只是在可视化上方便了,但如果我们需要在excel中整理系统的数据字典时这个解决方案包就派不上用 ...
- Android属性动画完全解析(下),Interpolator和ViewPropertyAnimator的用法
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/44171115 大家好,欢迎继续回到Android属性动画完全解析.在上一篇文章当中 ...
- Dynamics CRM2013 Form利用window.location.reload()进行全局刷新带来的问题及解决办法
CRM2013以后,表单的保存后变成了局部刷新而非全局刷新,但很多情况下我们需要刷新整个页面,通过刷新页面来使脚本执行或者业务规则执行来实现某些业务效果,一般我们会使用window.location. ...
- 【我的书】Unity Shader的书 — 目录(2016.5.19最后一次更新)
写在前面 感谢所有点进来看的朋友.没错,我目前打算写一本关于Unity Shader的书. 出书的目的有下面几个: 总结我接触Unity Shader以来的历程,给其他人一个借鉴.我非常明白学Shad ...