1

Why the following program doesn't block on the second read call?

int pid = fork(); if(pid) { int fifo = open("testfifo", O_RDWR); char buf[20]; while(1) { read(fifo, buf, 10); puts(buf); } } else { int fifo = open("testfifo", O_WRONLY); write(fifo, "teststring", 10); close(fifo); } return 0; 

The second read call continues returning 0 even though the fifo become empty and it should block on the read call.

Am I missing something?

The OS is Windows and the pipe has been created with a mknod testfifo p.

5
  • Do not ignore the return value of read(). Interpret 0 as "end of file", < 0 as an error. You should get eof here, you closed the pipe. Commented Aug 31, 2011 at 12:31
  • @Simone Apologies for my dodgy edit - obviously didn't intend to damage your question like that! Commented Aug 31, 2011 at 12:48
  • @Hans But what i want is the program to block on the read waiting other processes to write on the pipe Commented Aug 31, 2011 at 12:48
  • 1
    Is this native Windows code or is it running under Cygwin or any similar environment? If native, whose C runtime library are you using - Microsoft Visual Studio? Commented Sep 1, 2011 at 2:40
  • @Harry Johnston Is cygwin. However i solved the problem; i have simply to open and close the file each time in the server cycle. Commented Sep 1, 2011 at 3:43

2 Answers 2

4

I found, from another stackoverflow question, that i should open and close the "server" pipe, in this case the pipe of the parent process, each time; so here's the correct code:

int pid = fork(); if(pid) { char buf[20]; while(1) { int fifo = open("testfifo", O_RDWR); read(fifo, buf, 15); close(fifo); puts(buf), fflush(stdout); } } else { int fifo = open("testfifo", O_WRONLY); write(fifo, "teststring", 15); close(fifo); } 
Sign up to request clarification or add additional context in comments.

Comments

0

You did not close the file

EDIT: deleted something embarrassing.

1 Comment

Tried, but the problem still remain; actually I think that the fifo is closed by the system at the end of the process. Moreover if you look at the code, there is a infinite loop, so the close(fifo) you added is never executed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.