← 返回首页
Linux高级程序设计(五十七)
发表时间:2021-12-12 00:47:43
命名管道读写规律(非阻塞)

1.命名管道非阻塞读写规律

命名管道非阻塞读写规律如下: 1. 先以只读方式打开,如果没有进程已经为写而打开一个FIFO,只读open成功,并且open不阻塞。 2. 先以只写方式打开,如果没有进程已经为读而且打开一个FIFO,只写open出场返回-1。 3. read/write读写命名管道数据时不阻塞。 4. 通信过程中,如果读进程先退出,写进程向管道写入数据时会收到SIGPIPE信号,立刻退出。

实例: 测试只读非阻塞

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

int main(int argc, char *argv[])
{
    if (mkfifo("myfifo", 0664) != 0)
    { // 出错
        if (errno != EEXIST)
        {
            perror("erro to mkfifo:");
            exit(1);
        }
    }    

    int fd;
    //O_RDONLY以只读方式打开,并且使用非阻塞模式。
    fd = open("myfifo", O_RDONLY |O_NONBLOCK);
    if (fd == -1)
    {
        perror("error to open:");
        exit(1);
    }

    char buff[128]="";
    ssize_t bytes;
    //这句话不会输出,说明在open时已经阻塞.
    printf("--------start to read-------");

    if((bytes = read(fd,buff,sizeof(buff)))==-1){
        perror("error to read:");
        exit(1);
    }

    printf("buff=%s\n",buff);
    printf("bytes=%d\n",bytes);

    return 0;
}

运行结果:

[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
--------start to read-------buff=
bytes=0

测试只写非阻塞。

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

int main(int argc, char *argv[])
{
    if (mkfifo("myfifo", 0664) != 0)
    { // 出错
        if (errno != EEXIST)
        {
            perror("erro to mkfifo:");
            exit(1);
        }
    }    

    int fd;
    //O_RDONLY以只写方式打开,并且使用非阻塞模式
    fd = open("myfifo", O_WRONLY |O_NONBLOCK);
    if (fd == -1)
    {
        perror("error to open:");
        exit(1);
    }

    char buff[128]="";
    ssize_t bytes;

    //以下语句都不会打印...,说明在open函数阻塞。
    printf("------start to write---------");
    write(fd,"hello,world!\n",strlen("hello,world!\n"));
    printf("--------end of write-------");

    return 0;
}

运行结果:

程序会立刻退出.

[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
error to open:: No such device or address