python - 在进程终止前获取进程快照

标签 python unix ubuntu

我想执行命令行并获取其 /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)

最佳答案

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

此外,检查此片段的输出:

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),否则它将成为僵尸进程。被要求为那个 child 。这意味着如果你没有花哨的 SIGCHLD在你的程序中处理程序,你可以安全地对你 child 的 /proc/<pid> 做任何你想做的事。 wait(2) 之前的目录被称为。

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

关于python - 在进程终止前获取进程快照,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6728611/

相关文章:

python - 在 Python 中使用 API 调用运行需要很长时间的脚本的最佳方法

bash - 从输出中删除颜色

php - 在 Windows 中使用 PHP 和 Postgres 开发 Web 应用程序与在 Linux 中开发 Web 应用程序相同吗?

ubuntu - 通过 wine metaeditor.exe 通过命令行编译 MQL4

python - 如果没有动态添加,如何正确删除 Kivy 中的小部件

javascript - 在python服务器上执行程序并在html网页上动态更新结果

c - 如何像 nm 命令一样显示符号的类型?

c - 线程创建和子进程创建的系统调用有什么区别

linux - 如何使用 gksu gnome-schedule 设置工作目录

python - 列上的累计和百分比?