Perhaps the output buffer is not flushing correctly. I've encountered a very similar issue when doing multithreading and piping the output to a file--sometimes output would appear twice. Try adding this line to your main function:
setvbuf(stdout, NULL, _IONBF, 0);
This will force the output buffer to be flushed on each write.