如何在信号处理程序中找出受影响过程的PID

时间:2016-05-31 10:45:49

标签: python python-3.x signals

我有以下信号处理程序:

def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

信号处理程序注册如下:

signal.signal(signal.SIGINT, signal_handler)

如何在SIGINT发生时在信号处理程序中找出受影响的进程ID?

1 个答案:

答案 0 :(得分:2)

我建议使用os.getpid()

import os, sys, signal

def signal_handler(signal, frame):
    pid = os.getpid()
    print('You pressed Ctrl+C (pid = {0})'.format(pid))
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

参考:https://docs.python.org/3/library/os.html#os.getpid