tags:

views:

50

answers:

3

I am having problem debugging why n_bytes in read_from_fifo function in client.c doesn't correspond to the value written to the fifo. It should only write 25 bytes but it tries to read a lot more (1836020505 bytes (!) to be exact). Any idea why this is happening?

server.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include <sys/stat.h>

typedef enum { false, true } bool;

//first read the int with the number of bytes the data will have
//then read that number of bytes
bool read_from_fifo(int fd, char* var)
{
    int n_bytes;
    if (read(fd, &n_bytes, sizeof(int)))
    {
        printf("going to read %d bytes\n", n_bytes);
        if (read(fd, var, n_bytes))
            printf("read var\n");
        else {
            printf("error in read var. errno: %d\n", errno);
            exit(-1);
        }
    }

    return true;
}

int main()
{
    mkfifo("/tmp/foo", 0660);
    int fd = open("/tmp/foo", O_RDONLY);
    char var[100];
    read_from_fifo(fd, var);
    printf("var: %s\n", var);
    return 0;
}

client.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>

typedef enum { false, true } bool;

//first write to fd a int with the number of bytes that will be written afterwards
bool write_to_fifo(int fd, char* data)
{
    int n_bytes = (strlen(data)) * sizeof(char);
    printf("going to write %d bytes\n", n_bytes);
    if (write(fd, &n_bytes, sizeof(int) != -1))
        if (write(fd, data, n_bytes) != -1)
            return true;
    return false;
}


int main()
{
    int fd = open("/tmp/foo", O_WRONLY);
    char data[] = "some random string abcdef";
    write_to_fifo(fd, data);
    return 0;
}

Help is greatly appreciated. Thanks in advance.

+1  A: 

The return value for an error from read(2) is -1, not 0. So your if statement for the first 4-byte read, at least, is wrong.

bmargulies
That is correct, but that's not the real problem.
nunos
+1  A: 

Did you verify if nbytes printed by read_from_fifo() function displayed the correct value ? Just notice that on write(fd, data, n_bytes) you did not write the end of string char '\0', and whenever you read it by read(fd, var, n_bytes), you did not added a '\0' to the end of string just read, so the printf("var: %s\n", var); could display a not \0 ended string resulting unpredicted results.

Jorg B Jorge
A: 

I have found the solution myself.

The problem is a ')' believe it or not. The n_bytes variable is correct, the problem is that I am not writing that to the fifo.

this (write(fd, &n_bytes, sizeof(int) != -1))

should be this (write(fd, &n_bytes, sizeof(int)) != -1)

Thanks anyway for your answers.

nunos
jschmier
you are right, i miscopied from the source code.
nunos