【问题标题】:See stdin/stdout/stderr of a running process - Linux kernel查看正在运行的进程的 stdin/stdout/stderr - Linux 内核
【发布时间】:2015-02-03 16:29:11
【问题描述】:

有没有办法以简单的方式重定向/查看给定正在运行的进程的标准输入/标准输出/标准错误(通过 PID)?

我尝试了以下方法(假设 'pid' 包含正在运行的用户进程):

int foo(const void* data, struct file* file, unsigned fd)
{
    printf("Fd = %x\n", fd);
    return 0;
}
struct task_struct* task = pid_task(find_vpid(pid), PIDTYPE_PID);
struct files_struct* fs = task->files;
iterate_fd(fs, 0, foo, NULL);

我收到 3 次对 foo 的调用(这个过程可能有 3 个打开的文件,这是有道理的)但我无法真正读取它们(从文件指针)。

打印出来:

0
1
2

是否有可能以相当简单的方式实现我的要求?

谢谢

【问题讨论】:

    标签: linux linux-kernel


    【解决方案1】:

    首先,如果您可以更改您的架构,您可以在 screen、tmux、nohup 或 dtach 之类的东西下运行它,这将使您的生活更轻松。

    但是如果你有一个正在运行的程序,你可以使用strace 来监控它的内核调用,包括所有的读/写。您将需要限制它看到的内容(尝试-e),并且可能只过滤前 3 个 FD 的输出。还要加上-s,因为默认是限制记录数据的大小。比如:strace -p <PID> -e read,write -s 1000000

    【讨论】:

      【解决方案2】:

      你可以通过gdb来实现

      检查文件句柄 process() 是否已打开:

      $ ls -l /proc/6760/fd
      total 3
      lrwx—— 1 rjc rjc 64 Feb 27 15:32 0 -> /dev/pts/5
      l-wx—— 1 rjc rjc 64 Feb 27 15:32 1 -> /tmp/foo1
      lrwx—— 1 rjc rjc 64 Feb 27 15:32 2 -> /dev/pts/5
      

      现在运行 GDB:

      $ gdb -p 6760 /bin/cat
      GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
      Copyright (C) 2014 Free Software Foundation, Inc.
      [lots more license stuff snipped]
      Attaching to program: /bin/cat, process 6760
      [snip other stuff that’s not interesting now]
      
      (gdb) p close(1)
      $1 = 0
      

      提供一个新的文件名来获取输出 - process_log

      (gdb) p creat(“/tmp/process_log″, 0600)
      $2 = 1
      (gdb) q
      The program is running. Quit anyway (and detach it)? (y or n) y
      Detaching from program: /bin/cat, process 6760
      

      然后验证结果为:

      ls -l /proc/6760/fd/
      total 3
      lrwx—— 1 rjc rjc 64 2008-02-27 15:32 0 -> /dev/pts/5
      l-wx—— 1 rjc rjc 64 2008-02-27 15:32 1 -> /tmp/process_log <====
      lrwx—— 1 rjc rjc 64 2008-02-27 15:32 2 -> /dev/pts/5
      

      同理,你也可以重定向stdin、stderr。

      【讨论】:

        猜你喜欢
        • 2013-11-08
        • 2011-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-27
        • 1970-01-01
        • 2010-09-08
        • 1970-01-01
        相关资源
        最近更新 更多