Home > Mobile >  Message only being passed with fgets in named pipe
Message only being passed with fgets in named pipe

Time:10-16

Server.c

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

int main() {

    mkfifo("/tmp/fifox", 0666);
    char message[50];

    for(;;) {
      int fd = open("/tmp/fifox", O_RDONLY);
      read(fd, message, 50);
      printf("%s", message);
    }

    return 0;
}

Client.c

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

int main() {

    int fd = open("/tmp/fifox", O_WRONLY);
    char message[50];
    scanf("%s", message);
    //fgets(message, 50, stdin);

    write(fd, message, 50);
    close(fd);

    return 0;
}

Whenever I try to pass from client message with scanf then it's not being received on my server. Same thing happens whenever I do it like char message[50] = "test". It only works when I write fgets(message, 50, stdin);

CodePudding user response:

Probable cause is server side output issue. fgets includes a newline in the message, scanf does not.

Try this for printing the message:

printf("%s\n", message);

Or add fflush(stdout); after the printf.


Also, check return values of all input/read function calls! Also check return values of all output/write function calls, except "normal" printing to stdout or stderr (nobody checks those).

  •  Tags:  
  • c
  • Related