'How to read from named pipe?

I want to create a server client communication through named pipe. Everytime something comes to a server, I want to print the message and run server function - how do I only print when something gets sent? Could someone advise what I am doing wrong in the server file?

server

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

int server(int d) { return d;}
int main()
{
 mkfifo("/tmp/myfifo1", 0666);
 char buf[256];

 for(;;) {
   
    int fd = open("/tmp/myfifo1", O_RDONLY);
    int rd = read(fd, buf, sizeof(buf));
    if(fd < 0) {
      perror("error: open");
    }
    if(rd < 0) {
      perror("error: read");
    }
    if(rd > 1 ) {
      printf("%s", buf);
    }
    server(5);
    close(fd);
  }
    return 0;
}

client

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

int main()
{
    char *buf = "Hello from client";
    int fd = open("/tmp/myfifo1", O_WRONLY);
    int wr = write(fd, buf, sizeof(buf));
    if(fd < 0) {
      perror("error: open");
    }
    if(wr< 0) {
      perror("error: write");
    close(fd);
 
    return 0;
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source