Linux – Redirect stdout to a file when process is run in background

bashcentoscommand linelinuxstdout

How can I redirect the stdout of a program to a file when it's run in the background?

I have a program that generates output every second. When I run it normally and redirect to a file, the output is in that file as expected:

#./program > file.txt
#cat file.txt
 output
 output
 output
#

When I try to do the same thing in the background, the file will remain empty:

#./program > file.txt &
#cat file.txt
#

Best Answer

What about sh -c './program > file.txt; cat file.txt' & ?

Related Question