一、
当没有数据可读时
O_NONBLOCK disable:read调用阻塞,即进程暂停执行,一直等到有数据来到为止。
O_NONBLOCK disable:read调用阻塞,即进程暂停执行,一直等到有数据来到为止。
O_NONBLOCK enable:read调用返回-1,errno值为EAGAIN。
示例程序如下:
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
/************************************************************************* > File Name: process_.c > Author: Simba > Mail: dameng34@163.com > Created Time: Sat 23 Feb 2013 02:34:02 PM CST ************************************************************************/ #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); } 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,让父进程先被调度运行,而且读端文件状态标志设置为非阻塞,即立刻出错返回,如下。
simba@ubuntu:~/Documents/code/linux_programming/APUE/pipe$ ./pipe_block
read error: Resource temporarily unavailable
二、当管道满的时候
O_NONBLOCK disable: write调用阻塞,直到有进程读走数据
O_NONBLOCK enable:调用返回-1,errno值为EAGAIN
管道是一块内存缓冲区,可以写个小程序测试一下管道的容量Pipe Capacity:
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1 |