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

前端 未结 8 616
离开以前
离开以前 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:47

    Since I'm not allowed to edit Jauco's answer, I'll give the full answer that worked for me (Russell's page relies on un-guaranteed behaviour that, if you close file descriptor 1 for STDOUT, the next creat call will open FD 1.

    So, run a simple endless script like this:

    import time
    
    while True:
        print 'test'
        time.sleep(1)
    

    Save it to test.py, run with

    $ python test.py
    

    Get the PID:

    $ ps auxw | grep test.py
    

    Now, attach gdb:

    $ gdb -p (pid)
    

    and do the fd magic:

    (gdb) call creat("/tmp/stdout", 0600)
    $1 = 3
    (gdb) call dup2(3, 1)
    $2 = 1
    

    Now you can tail /tmp/stdout and see the output that used to go to STDOUT.

提交回复
热议问题