C无法读取fifo(命名管道)

时间:2016-04-06 01:04:03

标签: c systems-programming mkfifo

我创建了一个fifo,但我无法从中读取。有什么问题?这是代码和输出。如果我在没有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

1 个答案:

答案 0 :(得分:0)

  1. 问题是你关闭文件,
  2. 你可以尝试这个或者分叉另一个进程并读取文件,这主要是为什么名为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"); 
    
相关问题