How to check if there exists a process with a given pid in Python?

后端 未结 13 1274
名媛妹妹
名媛妹妹 2020-11-27 11:48

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 che

13条回答
  •  情书的邮戳
    2020-11-27 12:15

    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
    

提交回复
热议问题