mythic
mythic

Reputation: 935

How to write and read from a named pipe in C?

I have 2 programs (write.c and read.c). I want to continuously write to the named pipe from standard input, and read from it on the other end (and write to standard output). I've made something work, but it isn't working right. The program on the other end reads in the wrong order or reads special characters (so it reads more then it needs?). I also want to be able to compare the named pipe output to a certain string.

Anyways, here's the code from both files:

write.c:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFSIZE 512
#define err(mess) { fprintf(stderr,"Error: %s.", mess); exit(1); }

void main()
{
    int fd, n;

    char buf[BUFFSIZE];


    mkfifo("fifo_x", 0666);
    if ( (fd = open("fifo_x", O_WRONLY)) < 0)
        err("open")

    while( (n = read(STDIN_FILENO, buf, BUFFSIZE) ) > 0) {
        if ( write(fd, buf, strlen(buf)) != strlen(buf)) { 
            err("write");
        }
    }
    close(fd);
}

read.c:

#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFSIZE 512
#define err(mess) { fprintf(stderr,"Error: %s.", mess); exit(1); }

void main()
{
    int fd, n;
    char buf[BUFFSIZE];

    if ( (fd = open("fifo_x", O_RDONLY)) < 0)
        err("open")


    while( (n = read(fd, buf, BUFFSIZE) ) > 0) {

        if ( write(STDOUT_FILENO, buf, n) != n) { 
            exit(1);
        }
    }
    close(fd);
}

Example of input:

hello how are you
123 
test

Example of incorrect output:

hello how are you
b123
o how are you
btest
 how are you
b

Another example of input:

test
hi

And output:

test
hi
t

Upvotes: 11

Views: 25304

Answers (1)

Stargateur
Stargateur

Reputation: 26767

The buffer modify by read is not a valid c string so

write(fd, buf, strlen(buf)) != strlen(buf) // write.c

is undefined behaviour. You should do

write(fd, buf, n) != n

because you read n octet with read().

It's funny because you do it for read.c but not for write.c


The type of n must but ssize_t and not int, man read.


main() must return a int Declare main prototype

Upvotes: 7

Related Questions