Is it possible to read the output from any process using its PID?

Is it possible to attach a terminal to an already running process by using its PID in a similar fashion to using the fg command for jobs?


Solution 1:

You can get that process's standard file descriptors, e.g. stdout:

tail -f /proc/<pid>/fd/1

Solution 2:

There are a few options here. One is to redirect the output of the command to a file, and then use tail to view new lines that are added to that file in real time.

Another option is to launch your program inside of screen, which is a sort-of text-based terminal application. Screen sessions can be attached and detached, but are nominally meant only to be used by the same user, so if you want to share them between users.

Else if you wish you can trace the process and see what it is doing with strace:

strace -e trace=open -p 22254 -s 80 -o output.txt
  • -p PID: Attach to the process with the process ID PID and begin tracing.
  • -s SIZE: Specify the maximum string size to print (the default is 32).
  • -o filename: Write the trace output to the file filename rather than to screen (stderr).