在 Linux 中编程 - FIFO

Programming in Linux - FIFO

我已经创建了fifo,尝试写入:echo "text" > myfifo 并用我的程序阅读它。 但是当我写到 fifo 时没有任何显示。

我尝试了很多选项,关闭和打开 NON_BLOCK 模式等等,但似乎没有任何帮助。

#include <ctype.h>
#include <stdio.h> 
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

int main (int argc, char **argv)
{

int c;

int tab[argc/2];//decriptors
int i=0;
while ((c = getopt (argc, argv, "f:")) != -1) {
    switch (c) {
        case 'f':
            if (tab[i] = open(optarg, O_RDONLY| O_NONBLOCK) == -1) {
                perror(optarg);
                abort();
            }
            //dup(tab[i]);
            //printf(":::::%d==== %s\n",555,optarg);
            i++;
            break;

        default:
            abort();
    }
}
printf("----------------------\n");

char cTab[10];
int charsRead;
for(int j=0;j<=i;j++)
{
    charsRead = read(tab[j], cTab, 10);

    printf(" ==%d+++%s\n",tab[j],cTab);
    //write(tab[j],cTab,10);
}
for(int j=0;j<i;j++)

{
    close(tab[j]);
}

这个

      if (tab[i] = open(optarg, O_RDONLY| O_NONBLOCK) == -1) {

需要

      if ((tab[i] = open(optarg, O_RDONLY)) == -1) {

(可能不需要 O_NONBLOCK 标志,但您最严重的错误是您将布尔结果(0 或 1;不是文件描述符)分配给 tab[i]

最后但同样重要的是,对于

  printf(" ==%d+++%s\n",tab[j],cTab);

要工作,你需要在你读到的最后一个字符后放一个空字符:

  if(charsRead >= 0) 
        cTab[charsRead] = 0;

(您还需要确保始终有 space 作为终止空值:要求 9 个字符或为数组分配 11 个字符)。