Redirect stdout to a file when process is run in background
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
#
Solution 1:
What about sh -c './program > file.txt; cat file.txt' &
?
Solution 2:
When redirecting stdout to a text file, you are changing the stream type from console to file. The console output is unbuffered, while the file output is buffered. Until the program flushes the stdout device (file), the text will continue to buffer until the buffering threshold is reached. If the text "output\n" is printed every 2 seconds, and the threshold is 4,096 bytes, it would take nearly 20 minutes to see any output from the program in the file.