I've been trying to create a simple program which uses a named pipe to communicate between processes. I've tried doing this on OS X Yosemite as well as Ubuntu Linux 14.04 (virtualised on Parallels) and below is the code for a program which should have 3 processes which communicate via the same named pipe.
My Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
void proc1(char *named_pipe) {
printf("Proc 1\n");
int fd;
char *mess1;
mess1 = "Message from \"proc1\".";
fd = open(named_pipe, O_WRONLY);
if(fd == -1) {
printf("error : opening\n");
exit(-1);
}
printf("Opened\n");
if(write(fd, mess1, sizeof(mess1)) == -1) {
perror("error : writing\n");
exit(-1);
}
close(fd);
printf("End of Process 1.\n");
}
void proc2(char *named_pipe) {
int fd;
char buf[50];
char *mess2;
fd = open(named_pipe, O_RDONLY);
read(fd, buf, 50);
printf("Received : %s\n", buf);
close(fd);
mess2 = "Message from \"proc2\".";
fd = open(named_pipe, O_WRONLY);
write(fd, mess2, sizeof(mess2));
close(fd);
printf("End of Process 2.\n");
}
void proc3(char *named_pipe) {
int fd;
char buf[50];
fd = open(named_pipe, O_RDONLY);
read(fd, buf, 50);
printf("Received : %s\n", buf);
close(fd);
printf("End of Process 3.\n");
}
int main() {
char tube[4] = "tube";
printf("### Start of program ###\n");
if(mkfifo(tube, 0600) == -1) {
perror("Problem creating named pipe.\n");
exit(99);
}
proc1(tube);
proc2(tube);
proc3(tube);
printf("### End of program ###\n");
return 0;
}
My Output
### Start of program ###
Proc 1
And then nothing happens, apart from the cursor blinking indicating (?) that the program is still running. Thus, the code seems to loop infinitely every time I run this program without ever telling me why.
My Question
What really puzzles me though is that even a verified-to-be-working piece of code I found on this site while researching this issue also results in the same infinite loop/no output; see that code here. Could it then be an issue with my operating system? Bear in mind the exact same result occurs on both OSX and Ubuntu.
update
Solution
(Thanks to @Sami Kuhmonen)
I needed to run the 2 programs (from the linked code) at the same time. Feel a bit silly now!