Reputation: 61
I'm trying to read float values through a pipe as long as there is data in it. The problem is that the read function never returns 0 in my case, so my function never gets out of the loop.
Moreover, I cannot use library functions.
To give you the context : I want to create child processes which run the following function. Each float value is sent by the parent through the pipe and is read by one of the children processes which is supposed to sleep in order to let another child process read 1 other value and sleep. When a process wakes up, he's supposed to check if it can get a value from the pipe to sleep again, otherwise the loop ends and the child process is exited.
void worker(int * pip){
close(pip[1]);
float buffer;
while(read(pip[0], &buffer, sizeof(float)) != 0){
sleep(buffer);
}
exit(1);
}
Each value is written by the parent this way in a loop :
write(pip[1], &values[i], sizeof(float))
Upvotes: 0
Views: 463
Reputation: 1498
You should call close(pip[1]);
after parent write
all data.
The following code
could work:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void worker(int * pip){
close(pip[1]);
float buffer;
while(read(pip[0], &buffer, sizeof(float)) != 0){
printf("%f\n", buffer);
}
exit(1);
}
int main() {
int pip[2];
pipe(pip);
if (fork() == 0) {
worker(pip);
exit(1);
}
close(pip[0]);
float a[4] = {1.1, 2.2, 3.3, 4.4};
for (int i = 0; i != sizeof(a) / sizeof(a[0]); ++i)
write(pip[1], a + i, sizeof(a[0]));
close(pip[1]);
wait(NULL);
return 0;
}
Upvotes: 3