0

I just want to test some programs which use named pipes. I found some examples but they don't work as I want.

This code below works only when I open "myfifo" to read before opening to write. If I don't open to read before, it will create fifo, but won't open it. I think it shouldn't work like that.

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

#define MAX_LINE 80

int main(int argc, char** argv) {
   char line[MAX_LINE];
   int pipe;

   mkfifo("/tmp/myfifo", S_IRWXU);
   printf("Created fifo\n");

   //int rfd = open("/tmp/myfifo", O_RDONLY|O_NONBLOCK);   //works with that

   pipe = open("/tmp/myfifo", O_WRONLY);  // open a named pipe
   printf("Opened\n");

   printf("Enter line: ");  // get a line to send
   fgets(line, MAX_LINE, stdin);

   write(pipe, line, strlen(line));   // actually write out the data and close the pipe

   close(pipe);    // close the pipe
   return 0;
}

Also I tried to test this example: https://stackoverflow.com/a/2789967/7709706 and it couldn't open fifo as well. I don't know why.

I used MacOS and Linux.

Community
  • 1
  • 1
Yakimget
  • 25
  • 4
  • 7
    If you open a FIFO in write mode, it blocks until another process opens it for reading, unless you use non-blocking mode. if you try to do these in the same program, you'll never get to the second `open()` because you're blocked in the first one. – Barmar Apr 18 '17 at 15:08
  • 1
    So your request is "I found some code somewhere, debug it for me"? Sorry, that's not how it works. – too honest for this site Apr 18 '17 at 15:21
  • 1
    Note that it doesn't matter whether you open for reading or writing first; the open for reading won't return unless there's also a process with the FIFO open for writing (or attempting to open it for writing), and the open for writing won't return unless there's also a process with the FIFO open for reading (or attempting to open it for reading). A single process can open a FIFO for reading and writing (`O_RDWR`), but that's seldom the correct choice. You normally need (at least) two processes to work with a FIFO, therefore: (at least) one to read and (at least) one to write. – Jonathan Leffler Apr 18 '17 at 15:47
  • Using `O_NONBLOCK` does prevent blocking; that is often not what you really want, either. – Jonathan Leffler Apr 18 '17 at 15:49
  • It's not an answer but you should always test the return value of a system call and use for example perror/exit in case of failure to figure out what went wrong. – Fryz Apr 18 '17 at 18:46

0 Answers0