logoalt Hacker News

How can I read the standard output of an already-running process?

59 pointsby ibobev12/05/202530 commentsview on HN

Comments

theamklast Thursday at 4:34 PM

Raymond's posts are always fun to read, but it sometimes he focuses more on the "proper" methods, and does not even acknowledge that there are hacky workarounds.

Like for this case - sure, you cannot redefine the standard output handle, but that's not what the customer asked for, is it? They said "read" and I can see a whole bunch of ways to do so - ReadConsoleOutput + heuristic for scrolling, code inject into console host, attach debugger, set up detour on logging function, custom kernel module...

To be fair, as a MS support person, it's the exactly right thing to do. You don't want the person to start writing custom kernel module when they should redirect stdout on process start instead. But as a random internet reader, I'd love to read all about hacky ways to achieve the same!

show 1 reply
ranger_dangerlast Thursday at 1:46 PM

I know this article is for Windows, but if you're wondering if there's a way to do this on Linux, there is:

https://strace.io/

https://github.com/nelhage/reptyr

https://github.com/crigler/dtach

https://github.com/jerome-pouiller/reredirect

https://github.com/pasky/retty

show 6 replies
ameliuslast Thursday at 1:47 PM

Can't you attach to it from GDB?

show 1 reply
jeffrallenlast Thursday at 8:12 PM

strace (8).

bh0k4llast Thursday at 5:16 PM

How I use the script command to read the output of the last command and ask an LLM for help:

The following custom command is executed for starting the terminal

  /usr/bin/zsh -c 'export SCRIPT_LOG_FILE_NAME=$(date "+%m-%d-%y-%H-%M-%S-%N") && mkdir -p /tmp/script-log/ && script -f -q /tmp/script-log/$SCRIPT_LOG_FILE_NAME'



  export SCRIPT_LOG_FILE_NAME=$(date "+%m-%d-%y-%H-%M-%S-%N")
  mkdir -p /tmp/script-log/
  script -f -q /tmp/script-log/$SCRIPT_LOG_FILE_NAME
The date sub-command creates a unique filename for the current session and stores it in SCRIPT_LOG_FILE_NAME.

  export SCRIPT_LOG_FILE_NAME=$(date "+%m-%d-%y-%H-%M-%S-%N")
Create a folder in /tmp/script-log/.

  mkdir -p /tmp/script-log/
Script then writes the current terminal session to that file.

  script -f -q /tmp/script-log/$SCRIPT_LOG_FILE_NAME
Now any command run in this terminal knows where the last program wrote its output.

We can split the log at the last $PS1 prompt and feed the most recent chunk to a utility such as Simon W.'s llm.

Add the following to .zshrc (or …):

  alias z='tail -n 100 /tmp/script-log/$SCRIPT_LOG_FILE_NAME | llm -s "Fix it or similar" | pbcopy'


Essentially, run a command; if it fails, run z.
show 1 reply