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

I have 2 programs (write.c and read.c). I want to constantly write to a named pipe from standard input and read from it on the other end (and write to standard output). I did something, but it is not working properly. The program on the other end is reading in the wrong order or reading special characters (so that it reads more than it needs?). I also want to be able to compare the output of a named pipe with a specific string.

Anyway, here is 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);
}

Input Example:

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 input example:

test
hi

And the conclusion:

test
hi
t
+4
source share
1 answer

c,

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

- undefined.

write(fd, buf, n) != n

n read().

, read.c, write.c


n ssize_t, int, man read.


main() int

+4

Source: https://habr.com/ru/post/1662975/


All Articles