Is there a way to flush stdout of a running process

让人想犯罪 __ 提交于 2020-02-21 11:10:34

问题


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?


回答1:


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.




回答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 ;)



来源:https://stackoverflow.com/questions/30546183/is-there-a-way-to-flush-stdout-of-a-running-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!