3

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
#
11
  • Not the way I expect it to be. What program are you running?
    – slhck
    Commented Jul 19, 2012 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
    Commented Jul 19, 2012 at 19:48
  • 1
    Is it also empty when the program is finished?
    – Bernhard
    Commented Jul 19, 2012 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
    Commented Jul 19, 2012 at 20:11
  • 1
    What about sh -c './program > file.txt; cat file.txt' & ?
    – Lenik
    Commented Jul 21, 2012 at 14:21

2 Answers 2

3

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

2
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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .