Skip to content
Advertisement

Programming in Linux – FIFO

I have created fifo, try to write to it: echo "text" > myfifo and read it with my programm. But when I write to fifo nothing shows.

I have tried many options, turning off and on NON_BLOCK mode and so on but nothing seems to help.

#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==== %sn",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+++%sn",tab[j],cTab);
    //write(tab[j],cTab,10);
}
for(int j=0;j<i;j++)

{
    close(tab[j]);
}

Advertisement

Answer

This

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

needs to be

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

(there’s probably no need for the O_NONBLOCK flag, but your most grievous error is that you’re assigning a boolean result (0 or 1; not the file descriptor) to tab[i] )

Last but not least, for

  printf(" ==%d+++%sn",tab[j],cTab);

to work, you need to put a null character after the last character you read:

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

(Also you need to make sure there’s always space for the terminating null: either ask for 9 characters or allocate 11 for the array).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement