0

I am trying to create a simple fifo client/server. Whenever I compile the program and try to type some data in client, in server I am getting weird outputs such as: enter image description here How can I fix this?

server:

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

int main() {
    int fd;
    mkfifo("/tmp/my_fifo", 0666);
    for(;;){
        fd = open("/tmp/my_fifo", O_RDONLY);
        int d;
        char buf[64];
        read(fd, buf, sizeof(buf));
        sscanf(buf, "%d", &d);
        close(fd);
    }
    return 0;
}

client:

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

int main(){
    int fd;
    fd = open("/tmp/my_fifo", O_WRONLY);
    int d;
    scanf("%d", &d);
    char buf[32];
    sprintf(buf, "%d", d);
    write(fd, buf,strlen(buf));
    close(fd);
    return 0;
}
जलजनक
  • 3,072
  • 2
  • 24
  • 30
Dave
  • 1
  • 1
  • 9
  • 38
  • 3
    Do basic error checking. Check the return value of all functions. There could be failures on any of the steps which you will never know about without checks. That will make your code more robust and will help you debug where things may be going wrong. – kaylum Jan 24 '22 at 21:17
  • 1
    One possible issue: `write(fd, buf,strlen(buf));` does not write the terminating NUL character. And the server side does not explicit NUL terminate either. So the data read in the server is not a valid C string and thus the `sscanf` call has Undefined Behaviour. But my guess is there are also other failures which error checking will reveal. – kaylum Jan 24 '22 at 21:21
  • "*in server I am getting weird outputs*". The server code doesn't output anything. So please clarify how you are determining that. Please show the exact and full run log of both server and client. – kaylum Jan 24 '22 at 21:23
  • Your posted server code prints nothing – Support Ukraine Jan 24 '22 at 21:29

0 Answers0