python - 终止后获取进程信息

标签 python linux process popen pid

我需要一些有关终止进程的信息。

比如/proc中的utimeVMPeak是这样的:

proc.wait()
with open('/proc/%d/stat' % proc.pid, "r") as f:
    stat = str(f.read()).strip().split()
    # 14th column is utime, 15th column is stime (man 5 proc)                  
    cpu_time = int(stat[14]) + int(stat[15])
    return cpu_time

但是 Python Popen.wait() 释放了 PID,所以我会得到:

No such file or directory

我可以在终止后,或者等待终止而不释放PID吗? (我的意思是等待终止没有调用wait(),这将释放所有资源。)

如果你能帮助我,我将不胜感激。谢谢!

最佳答案

引用自man 5 proc:

/proc/[pid]
There is a numerical subdirectory for each running process; the subdirectory is named by the process ID.

终止的进程不再运行,其/proc/[pid] 目录(包括stat 文件)是< em>不再存在。

如果它要在那里,您可以在 调用 proc.wait() 之前将 PID 存储在变量中:

pid = proc.pid
proc.wait()
with open('/proc/%d/stat' % pid, "r") as f:

没有“就在终止前”事件; subprocess 等待,然后获取退出代码。

您可以使用 os.wait4() 进行自己的等待相反:

pid, status, resources = os.wait4(proc.pid, 0)
cpu_time = resources.ru_utime + resources.ru_stime

resources 是一个命名元组,参见 resource.getrusage()有关它支持的名称的列表。 .ru_utime.ru_stime 都是 float 。

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

相关文章:

Python Tkinter 计算器不会计算输入小部件中的文本

python - 将文档转换为 pdf 格式的有效方法

php - 在 PHP 中使用实时输出运行进程

java - 如何等待多线程 shell 脚本执行完成在我的 Web 服务中调用?

python - 修改多边形,使它们不重叠并且面积保持不变

python - Pandas agg 根据数据类型定义指标

linux - linux内核的of_clk_init中的__clk_of_table符号是什么

java - 如何使用 sched_setaffinity 清除线程关联性,这意味着我想将控制权交还给内核?

c++ - 我怎样才能完全理解操作系统的工作原理?

c++ - 如何在 C++ (Windows) 中同步两个进程?