11

I have a long-running process with stdout redirected to a file. E.g.:

./my-script.sh > file.txt &

Part of the stdout is still cached, but I would like to flush it to the file, to see the results earlier. Is there a way to do it?

W.F.
  • 13,888
  • 2
  • 34
  • 81

2 Answers2

13

The caching is handled by the libc. You can use the stdbuf command to change the buffer size:

stdbuf -o0 ./my-script.sh > file.txt &

-o0 sets the buffer size for stdout to 0. Probably you also want -e0 for stderr.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Yes, but my question was related to the program that is already running. Would it work in this case? – W.F. May 30 '15 at 12:48
  • No, the above command can be used to start a program with modified buffer sizes, it won't help if the process is already running – hek2mgl May 30 '15 at 12:50
  • 1
    You save my time, it's pretty useful to nohup redirect output to nohup.out – SDJSK Apr 13 '21 at 13:33
2

You can inspect the /proc/ filesystem and alter the file descriptor of stdout. For example:

gerard@droole ~$ bash -c '
    while [ true ]; do echo "."; sleep .5; done
' > ./myfile.txt &
[1] 3816
gerard@droole ~$ ls -la /proc/3816/fd/1 
l-wx------ 1 gerard gerard 64 May 30 14:55 /proc/3816/fd/1 -> /home/gerard/myfile.txt

You can see that stdout is symlinked to the file I specified on the command line. If you want to change it, you can simply link it to something else.

If you want to reroute this output, you can start a tee process, symlink the stdout of the process you're watching to a the stdin of the new process. You can reroute basically anything you want this way.

However, this is not very stable, as your programs output will be broken if you do not carefully restore its stdout file descriptor before the tee process is terminated.

But it is not impossible ;)

Gerard van Helden
  • 1,601
  • 10
  • 13