Reputation: 241
I'm trying to use named pipes. I have a process which reads info and another which writes info into the pipe.
This is the reduced code of my reader process:
main (int argc, char *argv[]) {
int fd, mkn;
char message[100];
if(unlink("aPipe") == -1) {
perror("Error unlinking:");
}
if((mkn = mknod("aPipe", S_IFIFO, 0)) < 0){
perror("Error mknod:");
}
if(chmod("aPipe", 0660)) {
perror("Error chmod:");
}
if(fd = open("aPipe", O_RDONLY) < 0) {
perror("Error abriendo el PIPE");
}
printf("going to read..\n");
close(fd);
}
but it gets stuck in this line: if(fd = open("aPipe", O_RDONLY) < 0)
forever, and I really dont understand why.
If you know which man page says what is happening here, please tell me :)
Upvotes: 0
Views: 4894
Reputation: 241
Here is the code:
Reader:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
readline(int fd, char *str) {
int n;
do {
n = read(fd, str, 1);
if(n == -1){
perror("Error reading:");
}
}
while(n > 0 && (str++) != NULL);
return(n > 0);
}
main (int argc, char *argv[]) {
int fd, mkn;
char message[100];
if(unlink("aPipe") == -1) {
perror("Error unlinking:");
}
if((mkn = mknod("aPipe", S_IFIFO, 0)) < 0){
perror("Error mknod:");
}
if(chmod("aPipe", 0660)) {
perror("Error chmod:");
}
if(fd = open("aPipe", O_RDONLY) < 0) {
perror("Error abriendo el PIPE");
}
printf("going to read..\n");
while(readline(fd,message))
printf("%s\n", message);
close(fd);
}
The writer:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
main (int argc, char *argv[]) {
int fd, messagelen,i;
char message[100];
sprintf(message, "Hello from PID %d", getpid());
messagelen = strlen(message) + 1;
do {
fd = open("aPipe", O_WRONLY|O_NDELAY);
if (fd == -1) {
perror("opening aPipe:");
sleep(1);
}
}
while(fd == -1);
for (i = 1; i < 4; i++) {
if(write(fd, message, messagelen) == -1) {
perror("Error writing:");
}
sleep(3);
}
close(fd);
}
I have to learn makefifo too, but after I understand this.
Thank you very much for your valuable help!
Upvotes: 2
Reputation: 2160
Is there any process writing to the FIFO? If no, this is the expected behaviour since you opened the FIFO RDONLY in blocking mode, the current process will not proceed until there is a process actually write to the FIFO.
Upvotes: 0
Reputation: 61389
FIFOs are a bit strange; open()
as a writer will block until there's a reader, and vice versa. Worse, just like a real pipe, when the writer closes its end the read end will return EOF forever; you have to close and reopen (blocking for the next reader). Or you open(fifo, O_RDWR)
and then you need some way to know when the writer is done such as having it use only a single line or having an in-band EOF packet.
Upvotes: 3