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.