Tom Maier
Tom Maier

Reputation: 403

How can I find out the PID of the affected process in signal handler

I've got the following signal handler:

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

The signal handler registration is the following:

signal.signal(signal.SIGINT, signal_handler)

How can I find out the affected process ID in the signal handler when the SIGINT happens?

Upvotes: 0

Views: 260

Answers (1)

leovp
leovp

Reputation: 4758

I suggest using 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)

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

Upvotes: 2

Related Questions