【问题标题】:Getting snapshot of process before it terminates在进程终止之前获取进程快照
【发布时间】:2011-07-18 04:24:51
【问题描述】:

我想执行一个命令行并获取其/proc 树的快照。关键是要尽可能多地了解这个过程。

一个潜在的问题是,该过程可能会在我完成复制内容之前终止。有什么建议可以解决这个问题吗?

这是我目前所拥有的

#!/usr/bin/python
#
# run command line and copy it's /proc tree to /tmp/proctree
# Example: copy_proc.py ls -l

import sys, os, shutil, subprocess as sp

if __name__=='__main__':
  f=open('/dev/null', 'w')
  p = sp.Popen(sys.argv[1:],stdout=f, stderr=f)
  if not os.path.exists('/tmp/proctree'):
    os.makedirs('/tmp/proctree')
  for f in os.listdir('/proc/'+str(p.pid)):
    shutil.copyfile(os.path.join('/proc',f), '/tmp/proctree/'+f)

【问题讨论】:

    标签: python unix ubuntu


    【解决方案1】:
    1. 每个符号链接也是一个文件。
    2. for f in os.listdir(path): do_something_with(f) 是错误的,除非你是你的 cwd 是 path

    另外,检查这个 sn-p 的输出:

    import os
    
    base = "/proc/%d" % os.getpid()
    for f in os.listdir(base):
        f = os.path.join(base, f)
        print "%-40s %5s %5s %5s" % (f, os.path.isfile(f), os.path.islink(f), os.path.isdir(f))
    

    现在关于问题的第一部分。当子进程终止时,它会变成僵尸进程,除非为该子进程调用wait(2)。这意味着如果您的程序中没有花哨的SIGCHLD 处理程序,您可以在调用wait(2) 之前安全地对您孩子的/proc/<pid> 目录执行任何操作。

    您也可以尝试将SIGSTOP 发送给您的孩子,制作您想要的快照,然后发送SIGCONT

    【讨论】:

    • 好点,isfile/isdir 实际上似乎按预期工作,我在isfile 行中有一个错误
    • 嗯...我想知道 /proc//maps 在进程变成僵尸时是否会被清除。我得到它是空的,这不是我所期望的
    猜你喜欢
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多