简体   繁体   English

创建PIPE块

[英]Creating PIPE blocks

I created a PIPE using the below code. 我使用以下代码创建了PIPE。 But there is something wrong when the program runs fd = open(FIFO, O_RDONLY); 但是当程序运行fd = open(FIFO, O_RDONLY); . The phenomenon is blocking. 该现象正在阻止。 Could someone give me some advice? 有人可以给我一些建议吗? Thanks a lot . 非常感谢 。

#include<errno.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#define FIFO "/tmp/test"

int main(int argc, char** argv)
{
    char buf_r[100];
    int fd;
    int nread;
    if((mkfifo(FIFO, O_CREAT) < 0) && (errno != EEXIST))
    {
            printf("can not create FIFO\n");
            exit(1);
    }

    printf("Prepare read data\n");
    fd = open(FIFO, O_RDONLY);
    if(fd == -1)
    {
            exit(1);
    }

    while(1)
    {
            if((nread = read(fd, buf_r, 100)) == -1)
            {
                    if(errno == EAGAIN) printf("No data\n");
            }

            if(buf_r[0]=='Q') break;

            buf_r[nread]=0;
            printf("data is:%s\n", buf_r);
            sleep(1);
    }

}

Opening a FIFO blocks until a "communication peer" is connected to the FIFO as well so that the pipe is successfully established. 打开FIFO块,直到“通信对等体”也连接到FIFO,以便成功建立管道为止。

BTW, when creating the FIFO fails, you should output (at most) a warning and continue - there are chances that the FIFO already exists and can be reused. 顺便说一句,当创建FIFO失败时,您应该最多输出警告并继续-FIFO已经存在并且可以重复使用的机会。 And maybe /root/test/test is not the best place for this FIFO... 也许/root/test/test不是此FIFO的最佳位置...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM