如何在Python中检查是否存在具有给定pid的进程? [英] How to check if there exists a process with a given pid in Python?

查看:88
本文介绍了如何在Python中检查是否存在具有给定pid的进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以检查pid是否与有效进程相对应?我从os.getpid()以外的其他来源获取了一个pid,我需要检查计算机上是否不存在具有该pid的进程.

Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from os.getpid() and I need to check to see if a process with that pid doesn't exist on the machine.

我需要它可以在Unix和Windows中使用.我还在检查PID是否未使用.

I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.

推荐答案

如果pid没有运行,则向pid发送信号0将引发OSError异常,否则不执行任何操作.

Sending signal 0 to a pid will raise an OSError exception if the pid is not running, and do nothing otherwise.

import os

def check_pid(pid):        
    """ Check For the existence of a unix pid. """
    try:
        os.kill(pid, 0)
    except OSError:
        return False
    else:
        return True

这篇关于如何在Python中检查是否存在具有给定pid的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆