Reputation: 1060
I'm writing a C++ program for class that requires a set of N child processes to communicate with their parent process on a Unix-based system. To that end, I declared two arrays of N pipes, one for each direction of communication, before forking the process:
int pipesToParent[N][2];
int pipesToChild[N][2];
... // for int i = 0 to N-1, pipe(pipesToParent[i]), pipe(pipesToChild[i]),
// fork(), yada yada, I included error checking and everything.
int pipesToChild[N][2];
Most of the code for the parent process is in a while loop; near the beginning of this loop, it reads a message from a particular process:
read(pipesToParent[processToServe][READ_END], charArray, BUF_SIZE);
The first time it goes through the loop, reading a message from process X, it works fine. Then it's instructed to do the same for process Y, the message from which contains exactly the same sort of data as process X (I have each process cout its message when it writes it to its pipe), and the process just stops. It doesn't exit, it just stays frozen at that line. I've tried everything I can think of to figure out what might be wrong with the message I'm sending, but it all looks just fine. What's going on here?
(Sorry if my detail's insufficient; I couldn't figure out what else I'd have to include and what I could remove to paste something that'd reproduce the problem.)
ETA:
The child process has its own internal while loop, in which it reads from its own pipe:
read(pipesToChild[thisProcessNumber][READ_END], charArray, BUF_SIZE);
If the parent's ready, it'll send its message:
write(pipesToParent[thisProcessNumber][WRITE_END], message, BUF_SIZE);
Some tinkering has revealed that process Y, much like the parent, is going through this loop once fine, then getting stuck on the read the second time. What exactly would flushing do, and can I do it if I wrote to/read from the pipe this way? (If it's relevant, I've #included cstdlib, but not cstdio.)
Upvotes: 0
Views: 2722
Reputation: 6181
Seems like deadlock to me - both your processes are waiting for another one to write something - but none of them actually writes anything, so everything stops. Make sure that your comunication design is deadlock-free (eg. clients reding conantly and writing only on reading READY comunicate, and server reading only fter writing READ comunicate). You might also consider going to non-blocking pipes.
As far as i know pipes created with pipe() call are unbuffered - the only buffer involved is pipe buffer, but as this is the same buffer from which reading in target app is done, it cannot create comunnication problems. Application-level happens only if you map file descriptors to C-like FILE pointers, but it seems it's not the case.
If you still think that everything is ok, post minimal compilable code that shows this behavior, so I can perhaps say more.
EDIT:
Since you accepted an answer, it would be nice if you mentioned also which solution (if any) solved your problem.
Upvotes: 1