This is some pseudo code of what I’m trying to achieve:
fork
in the child, dup2 a output descriptor to a file then exec a different program
in parent, kill the child after a period of time
The problem is though that after I kill the child the output file is empty even though the child has written to it at some stage. What am I doing wrong? I don’t want to wait for the child but I also don’t want it to reverse what it’s already written to file.
If your child dies as a result of a signal, it won’t flush any buffers, that’s why you don’t see any output. There are solutions for this
Of course, the third option is rather silly: the child signaling the parent could be replaced by simply exiting.
Edit
In light of edited question and comments
stdio(printf, fwrite etc.), for reasons of I/O efficiency uses some buffers. That is, when you do a simple write, the low-level operation doesn’t happen right away. The data is copied to some buffer and later, when the library deems it necessary (full buffers or something else) the buffers will be flushed – stuff is going to be written.Now, when a program calls
exit(3)(normal process termination) on of the things that happens is thatstdiobuffers are flushed. If a program dies as a result of a signal,stdiobuffers aren’t flushed and the memory is simply claimed by the OS.If you don’t have control over the programs you
exec(say you’re a shell) you can’t be sure they will do their thing if you kill them. That is, it’s not your responsibility. If however you do have control over them (you said something about a pipe) you can simply signal through the pipe some sequence that will make the children callexit(3).