linux系统编程之管道(二):管道读写规则和Pipe Capacity、PIPE_BUF

一、 当没有数据可读时
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: [email protected]
    > 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
  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值