I am trying to understand using pipes in C, specifically writing and reading integers. I have a parent process that creates 3 child processes. Two of the child processes calculate numbers and write them to a pipe. The third process reads from both pipes and then displays. Sounds simple right?
I found this post: How to send integer with pipe between two processes! on how to send integers through pipes and followed it, but I am not producing the correct output.
Edit: for further clarification, I initiate the pipes like so:
int p1[2]; //pipe1
int p2[2]; //pipe2
pipe(p1); //intialize pipe1 for between process 1 & 3
pipe(p2); //initialize pipe2 for between process 2 & 3
After some debugging, I notice that the wrong number is being written to the pipe. This is how I am writing an int to the pipe:
int c0 = 18;
write(p2[1], &c0, sizeof(c0));
and this is how I am reading:
int disp[4];
read(p1[0], &disp[0], sizeof(disp[0]));
and so on until the array is full.
Now instead of writing something like 14 to the pipe, it writes a large number like 17462. I am assuming that it is writing the address, right? If so, how would I write the actual integer to the pipe? Should I remove the '&' from the statements, because doing that gives me errors about casting. Any tips, advice, comments are always appreciated. Thanks.
c0? Also did you check the return value ofread? It should return the number of bytes read if successful. - Matti Virkkunendisp[0]is not valid unless it returnssizeof(int). On Unix, any read or write -like system call can fail at any time, and that can result in a partial read or write. You must check the return value. - Matti Virkkunenread()andwrite()call... I would have expected you to be suing the same pair of fds from the samepipe()call? Could just be that it got passed around and named differently, but worth asking. - FatalError