Search code examples
cnamed-pipespollingfile-descriptor

Checking for EOF when using read() function


This is my first time working with reading from file descriptors and I've been testing through trial and error for about 3 hours now, and I almost have my reader working! I just need a little bit of help on checking for EOF on a named pipe.

Ok so i'm opening a (well multiple) named pipe like this:

fds[j].fd = open(pipeNameo, O_RDWR) ; // storing it into my file descriptor array

then I am polling the named pipes to see if anything has come through (poll is within a loop):

int ret = poll(fds, numOfPipesUsed, timeout_msecs);

And when something does come through I process the file by sending the file descriptor that was written to over to this function:

int processFileDes( int fd )
{
    char buf[10] ;

    read(fd, buf, 1) ;
    char curr = buf[0] ;
    while (curr != EOF)
    {

        if ( curr == ' ')
        {
            // do nothing it is a space
        }
        else if ( curr == '\n')
        {
            printf("NEW LINE!\n") ;
        }
        else
        {
            int num = curr - '0' ; // turns char number into an int
            printf("Curr Num: %d\n", num) ;
        }

        printf("BEFORE\n"); // Gets stuck here when EOF, this is the string of output
        read(fd, buf, 1) ;
        printf("AFTER\n") ;

        curr = buf[0] ;
    }
printf("Success!\n") ; // this is never printed
return 0 ;
}

Everything works perfectly fine, except the read() function gets stuck (waiting for a return I imagine) once all characters have already been read. Where an EOF is supposed to be. I need to be able to check for EOF .

I tried a workaround that stopped my program from reading by counting the number of characters read (since I know the size of the input), and it would have worked, only thing is when there is a space after the last char it causes my looped poll to return a 1 and run the processFile() all over again on the remaining spaces (not valid input) left to be read.

Please help :')

The input is just a matrix of numbers like this:

0 1 1
2 0 3
1 0 0

Solution

  • you need to open nonblocking as a pipe will wait for data to become available:

    fds[j].fd = open(pipeNameo, O_RDWR | O_NONBLOCK);