Fixing race condition between stdout and stderr