命名管道打开规则

结论
一、当前为了读而打开 FIFO 时
O_NONBLOCK disable:open 调用阻塞,直到有进程为写而打开该 FIFO
O_NONBLOCK enable: open 调用返回文件描述符

二、当前为了写而打开 FIFO 时
O_NONBLOCK disable:open 调用阻塞,直到有进程为读而打开该 FIFO
O_NONBLOCK enable: open 调用返回 -1,errno 值为 ENXIO(6)

验证如下:
1、O_NONBLOCK disable:open 调用阻塞,直到有进程为写而打开该 FIFO

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MYFIFO  "./myfifo"

int main()
{
  int fd = -1;

  if (-1 == access(MYFIFO, F_OK)
    && -1 == mkfifo(MYFIFO, 0664))
  {
    perror("mkfifo error");
    return EXIT_FAILURE;
  }

  fd = open(MYFIFO, O_RDONLY);
  printf("open %s for reading, fd: %d\n", MYFIFO, fd);

  if (fd >= 0)
    close(fd);

  return 0;
}

2、O_NONBLOCK enable: open 调用返回文件描述符

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MYFIFO  "./myfifo"

int main()
{
  int fd = -1;

  if (-1 == access(MYFIFO, F_OK)
    && -1 == mkfifo(MYFIFO, 0664))
  {
    perror("mkfifo error");
    return EXIT_FAILURE;
  }

  fd = open(MYFIFO, O_RDONLY | O_NONBLOCK);
  printf("open %s for reading, fd: %d\n", MYFIFO, fd);

  if (fd >= 0)
    close(fd);

  return 0;
}
/*
 * open ./myfifo for reading, fd: 3
 */

3、O_NONBLOCK disable:open 调用阻塞,直到有进程为读而打开该 FIFO

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MYFIFO  "./myfifo"

int main()
{
  int fd = -1;

  if (-1 == access(MYFIFO, F_OK)
    && -1 == mkfifo(MYFIFO, 0664))
  {
    perror("mkfifo error");
    return EXIT_FAILURE;
  }

  fd = open(MYFIFO, O_WRONLY);
  printf("open %s for writing, fd: %d\n", MYFIFO, fd);

  if (fd >= 0)
    close(fd);

  return 0;
}

4、O_NONBLOCK enable: open 调用返回 -1,errno 值为 ENXIO(6)

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MYFIFO  "./myfifo"

int main()
{
  int fd = -1;

  if (-1 == access(MYFIFO, F_OK)
    && -1 == mkfifo(MYFIFO, 0664))
  {
    perror("mkfifo error");
    return EXIT_FAILURE;
  }

  fd = open(MYFIFO, O_WRONLY | O_NONBLOCK);
  if (fd < 0)
  {
    perror("open error");
    printf("errno: %d\n", errno);
    return EXIT_FAILURE;
  }

  printf("open %s for writing, fd: %d\n", MYFIFO, fd);

  if (fd >= 0)
    close(fd);

  return 0;
}
/*
 * open error: No such device or address
 * errno: 6
 */
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值