I have a parent process that forks and execs a child process, but before that it routes the child's stdout to a file descriptor cout_file
through a pipe.
Then the parent process listens through this pipe to the stdout of the child like so:
int status;
size_t buffer_size = 0;
char buffer [1024];
do
{
LOG(1)
while( (buffer_size = fread(buffer, sizeof(char), sizeof(char)*1024, cout_file)) !=0)
{
LOG(2)
LOG(std::string(buffer, buffer_size))
}
}while(waitpid(child_pid,&status, WNOHANG) != -1);
//read one more time
LOG(3)
while( (buffer_size = fread(buffer, sizeof(char), sizeof(char)*1024, cout_file)) !=0)
{
LOG(4)
LOG(std::string(buffer, buffer_size))
}
The script (child process) that is executed does this:
sys.stdout.write("BLABLABLA")
sys.stdout.flush()
time.sleep(3) #3 seconds
exit(0)
All of this works as expected 90% of the time, but there's a 10% of the time where the parent process does not see BLABLABLA
i.e. does not see the output of neither LOG(2)
nor LOG(4)
When if fails I see the following output
1 <---- at time t
1
.
.
1
3 <--- at time t+3 sec
So somehow, the script is writing to its stdout, but the parent process misses it.
The above code, has been working for few years now, and I noticed this behaviour recently, can anyone shed some light on what might be going wrong?