【问题标题】:C can't read from fifo (named pipe)C 无法从 fifo 读取(命名管道)
【发布时间】:2016-04-06 09:16:27
【问题描述】:

我创建了一个先进先出,但我无法从中读取。有什么问题?这是代码和输出。如果我在没有 O_NONBLOCK 程序的情况下使用 O_RDONLY ,请等待。

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

【问题讨论】:

  • 管道不存储消息。一旦你关闭文件描述符,你写给它的消息就会被丢弃。管道需要消费者在读,而生产者在写。

标签: c systems-programming mkfifo


【解决方案1】:
  1. 问题是你关闭了文件,

你可以试试这个或 fork 另一个进程并读取文件,这就是为什么命名 fifos 用于进程间通信的主要原因

此链接详细解释How to send a simple string between two programs using pipes?

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"); 

【讨论】:

    猜你喜欢
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多