How can a process intercept stdout and stderr of another process on Linux?

前端 未结 8 598
离开以前
离开以前 2020-11-27 11:23

I have some scripts that ought to have stopped running but hang around forever. Is there some way I can figure out what they\'re writing to STDOUT and STDERR in a readable

相关标签:
8条回答
  • 2020-11-27 11:55

    strace outputs a lot less with just -ewrite (and not the =1 suffix). And it's a bit simpler than the GDB method, IMO.

    I used it to see the progress of an existing MythTV encoding job (sudo because I don't own the encoding process):

    $ ps -aef | grep -i handbrake
    mythtv   25089 25085 99 16:01 ?        00:53:43 /usr/bin/HandBrakeCLI -i /var/lib/mythtv/recordings/1061_20111230122900.mpg -o /var/lib/mythtv/recordings/1061_20111230122900.mp4 -e x264 -b 1500 -E faac -B 256 -R 48 -w 720
    jward    25293 20229  0 16:30 pts/1    00:00:00 grep --color=auto -i handbr
    
    $ sudo strace -ewrite -p 25089
    Process 25089 attached - interrupt to quit
    write(1, "\rEncoding: task 1 of 1, 70.75 % "..., 73) = 73
    write(1, "\rEncoding: task 1 of 1, 70.76 % "..., 73) = 73
    write(1, "\rEncoding: task 1 of 1, 70.77 % "..., 73) = 73
    write(1, "\rEncoding: task 1 of 1, 70.78 % "..., 73) = 73^C
    
    0 讨论(0)
  • You don't state your operating system, but I'm going to take a stab and say "Linux".

    Seeing what is being written to stderr and stdout is probably not going to help. If it is useful, you could use tee(1) before you start the script to take a copy of stderr and stdout.

    You can use ps(1) to look for wchan. This tells you what the process is waiting for. If you look at the strace output, you can ignore the bulk of the output and identify the last (blocked) system call. If it is an operation on a file handle, you can go backwards in the output and identify the underlying object (file, socket, pipe, etc.) From there the answer is likely to be clear.

    You can also send the process a signal that causes it to dump core, and then use the debugger and the core file to get a stack trace.

    0 讨论(0)
提交回复
热议问题