3
2
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
#
Not the way I expect it to be. What program are you running? – slhck – 2012-07-19T19:44:16.887
The program itself is irrelevant but is a simple executable that checks something every second and writes the current value to stdout. – Rauffle – 2012-07-19T19:48:41.620
1Is it also empty when the program is finished? – Bernhard – 2012-07-19T19:53:19.687
@Rauffle I guess the program itself may be not irrelevant. Normally, you should have the content in your file. Are you sure the program outputs to STDOUT and not e.g. to STDERR? – speakr – 2012-07-19T19:55:28.013
Does the
jobs
command show that your program is running? It may be stopped for some reason. – garyjohn – 2012-07-19T19:57:50.487Tried with another program that prints to stdout and it's the same thing. If I direct stdout to a file but run it in the foreground the file will have content. If I run it in the background, the file remains empty even after the program finishes running. I'm rather new to CentOS, is this perhaps some kind of 'feature' of the OS? – Rauffle – 2012-07-19T20:00:24.507
1Can you give us more detail on the actual program you are running? Ordinarily, running in the background should make no difference. – chepner – 2012-07-19T20:11:32.260
Maybe your program needs to take input from StdIn and crashed because it's not connected? – billc.cn – 2012-07-19T23:06:19.100
1What about
sh -c './program > file.txt; cat file.txt' &
? – Xiè Jìléi – 2012-07-21T14:21:09.913@Xie I've since found a workaround to achieve what I wanted, but this worked (modified to "sh -c './program > file.txt' &"). Want to submit it as an answer? – Rauffle – 2012-07-25T17:40:12.023
@Rauffle Done! :) – Xiè Jìléi – 2012-07-26T00:39:13.907