Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
#
share|improve this question
    
Not the way I expect it to be. What program are you running? –  slhck Jul 19 '12 at 19:44
    
The program itself is irrelevant but is a simple executable that checks something every second and writes the current value to stdout. –  Rauffle Jul 19 '12 at 19:48
1  
Is it also empty when the program is finished? –  Bernhard Jul 19 '12 at 19:53
1  
Can you give us more detail on the actual program you are running? Ordinarily, running in the background should make no difference. –  chepner Jul 19 '12 at 20:11
1  
What about sh -c './program > file.txt; cat file.txt' & ? –  Xiè Jìléi Jul 21 '12 at 14:21

2 Answers 2

up vote 3 down vote accepted

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

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.