获取进程的PID
- 查看进程PID的命令是
ps -ef | grep 进程名称
- 问题:在多进程运行时同一个进程名称的pid对应多个pid
- 解决:根据PPID(父类pid)有无PPID来判断是否是根pid
例如文章来源:https://www.toymoban.com/news/detail-665673.html
ps -ef | grep -v grep| grep -E "Baking|PPID"
输出文章来源地址https://www.toymoban.com/news/detail-665673.html
UID PID PPID C STIME TTY TIME CMD
root 69603 275638 86 15:06 pts/0 00:00:06 python Baking.py 1111111
root 69605 69603 89 15:06 pts/0 00:00:06 python Baking.py 1111111
root 69610 69605 87 15:06 pts/0 00:00:06 python Baking.py 1111111
root 275638 2512 88 14:32 pts/0 00:30:21 python Baking.py 1111111
获取进程的pid
def get_process_id(process_name):
"""
获取进程PID,获取在多进程运行时主pid
:param process_name: 进程的名称
:return: 进程的 pid / 多进程的主 pid
"""
cmd = "ps -ef | grep \\ " + process_name + " | grep -v grep | awk '{print $2\" \"$3}'"
out = os.popen(cmd)
pids = out.read().strip('\n')
pid_map_ppid = {}
for pid_ppid in pids.split("\n"):
pid, ppid = pid_ppid.split(' ')
pid_map_ppid[pid] = ppid
if not pid_map_ppid:
return False
# 判断是否是多进程的主进程
pid = pid_map_ppid.keys()[0]
while pid_map_ppid.get(pid_map_ppid.get(pid)):
pid = pid_map_ppid.get(pid)
return pid
到了这里,关于【Centos】【python】获取进程的PID的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!