Crysis85
Crysis85

Reputation: 345

Reading FIFOs, resource temporary unavailable

I have a problem with a multithreaded program. Basically I'm using fifos to pass messages between threads

This is the thread that read from the pipe:

thread_args args = (thread_args) *arguments;
char* fifo_buffer = calloc (FIFO_SIZE, sizeof(char));
int flag;
int fifo_win_to_send = open(args.fifo_names[FIFO_WTS], O_RDONLY);
if (fifo_win_to_send < 0) {
    perror("fifo: error opening fifo");
    exit(1);
}

flag = fcntl(fifo_win_to_send, F_GETFL);
fcntl(fifo_win_to_send, F_SETFL, flag | O_NONBLOCK | O_NDELAY);

if (read( fifo_win_to_send, fifo_buffer, FIFO_SIZE) <= 0) {
            perror("fifo: error reading window to sender fifo");
            exit(1);
}
if (VERBOSE_SENDER) {
            printf("Read %s from fifo window_to_sender", fifo_buffer);
            fflush(stdout);
}

and the "writing thread":

char * fifo_buffer = calloc(FIFO_SIZE, sizeof(char));
thread_args args = (thread_args) *arguments;
int fifo_win_to_send = open(args.fifo_names[FIFO_WTS], O_WRONLY);
    if (fifo_win_to_send < 0) {
        perror("fifo: error opening fifo");
        exit(1);
    }

*fifo_buffer = 'A';
memcpy(fifo_buffer+1, &sequence_number, sizeof(int));
write( fifo_win_to_send, fifo_buffer, FIFO_SIZE);
if (VERBOSE_FIFO) {
    printf("From window to send:%s\n", fifo_buffer);
    fflush(stdout);
}

The fifo files are created in the main() before threads are spawned:

mkdir("temp",0777);
char * fifo_id[6];
for(i=0;i<6;i++)  {
    fifo_id[i]=calloc(100,sizeof(char));
}
fifo_id[FIFO_WTS] = strcpy(fifo_id[FIFO_WTS], "temp/window_to_sender");
if(mkfifo(fifo_id[FIFO_WTS], 0777)) {
    if(errno!=EEXIST) {
        perror("fifo: Cannot create named pipe");
        exit(1);
    }
}

The error occours running the program when trying to read from the fifo. The console reads "fifo: error reading window to sender fifo: Resource temporarily unavailable" the read should be "non blocking" but I've no idea if it's correct or what seems to be the problem. (first time trying to use both threads and fifos so I may have made sort of a mess...)

Upvotes: 1

Views: 3758

Answers (1)

Crysis85
Crysis85

Reputation: 345

I think i found the problem. Since is non blocking when there is no data returns the error EAGAIN, so writing something like

if (read( fifo_win_to_send, fifo_buffer, FIFO_SIZE) <= 0 && errno != EAGAIN) {
            perror("fifo: error reading window to sender fifo");
            exit(1);
}

fixes the problem!

Upvotes: 4

Related Questions