C can';t从fifo读取(命名管道)

C can';t从fifo读取(命名管道),c,systems-programming,mkfifo,C,Systems Programming,Mkfifo,我创建了一个fifo,但我不能从中读取。有什么问题吗?这是一个代码和输出。如果我只使用O_RDONLY而不使用O_NONBLOCK程序,请稍候 pid_t p; int fd; char str[]="sample"; mkfifo("myfifo", S_IRUSR | S_IWUSR); fd = open("myfifo", O_RDWR); printf("write %d byte\n", write(fd, str, 5)); close(fd); fd = open("m

我创建了一个fifo,但我不能从中读取。有什么问题吗?这是一个代码和输出。如果我只使用O_RDONLY而不使用O_NONBLOCK程序,请稍候

pid_t p;
int fd;
char str[]="sample";

mkfifo("myfifo", S_IRUSR | S_IWUSR);

fd = open("myfifo", O_RDWR);

printf("write %d byte\n", write(fd, str, 5));

close(fd);

fd = open("myfifo", O_RDONLY | O_NONBLOCK);

printf("read %d byte\n",read(fd, str, 6));

close(fd);

unlink("myfifo");
输出:

write 5 byte
read 0 byte
  • 问题是你要关闭文件
  • 您可以尝试这样做,也可以分叉另一个进程并读取文件,这就是为什么命名FIFO用于进程间通信的主要原因

    此链接详细解释了


    管道不存储消息。一旦关闭文件描述符,您写入其中的消息将被丢弃。管道需要消费者在阅读,而生产者在写作。
    pid_t p;
    int fd;
    char str[]="sample";
    
    mkfifo("myfifo", S_IRUSR | S_IWUSR);
    
    fd = open("myfifo", O_RDWR);
    
    printf("write %d byte\n", write(fd, str, 5));
    
    printf("read %d byte\n",read(fd, str, 6));
    
    close(fd);
    
    unlink("myfifo");