problem with fifos linux

Posted by nunos on Stack Overflow See other posts from Stack Overflow or by nunos
Published on 2010-05-30T00:56:04Z Indexed on 2010/05/30 1:02 UTC
Read the original article Hit count: 262

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about c

    Related posts about fifo