I have written this code:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#define N 10
int fd[2];
void son ()
{
int data=0;
if(read(fd[0], &data, sizeof(int))==sizeof(int))
fprintf(stderr,"%d\n",data);
else
fprintf(stderr,"Read failed\n");
}
int main(int argc, char** argv)
{
pid_t sons[N];
pipe(fd);
int data=5;
for(unsigned int i=0; i<N;i++)
{
sons[i]=fork();
if(!sons[i])
{
son();
break;
}
}
write(fd[1], &data, sizeof(int));
data=6;
}
If I try executing it, I get 10 times printed “5”.
What happened? Why all processes have read the same data? Can’t the data be read just once? I thought the reader process was consuming the data read.
I modified the code this way:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#define N 10
int fd[2];
void son ()
{
int data=0;
if(read(fd[0], &data, sizeof(int))==sizeof(int))
fprintf(stderr,"%d\n",data);
else
fprintf(stderr,"Read failed\n");
if(read(fd[0], &data, sizeof(int))==sizeof(int))
fprintf(stderr,"%d\n",data);
else
fprintf(stderr,"Read failed\n");
}
int main(int argc, char** argv)
{
pid_t sons[N];
pipe(fd);
int data=5;
for(unsigned int i=0; i<N;i++)
{
sons[i]=fork();
if(!sons[i])
{
son();
break;
}
}
write(fd[1], &data, sizeof(int));
data=6;
write(fd[1], &data, sizeof(int));
return 0;
}
So I write/read two times, the output I get is “5” and “6”, just once, doesn’t happen that all the 10 processes can read the pipe.Why this?
When you fork() you execute son(), then break out of the loop – but that is not the end of the child process! The child then continues and writes to fd[1].