Ivan Kolesnikov
Ivan Kolesnikov

Reputation: 1811

How to get id of process from which came signal in Python?

Please see following Python code:

def Handler(signum, frame):
    #do something
signal.signal(signal.SIGCHLD, Handler)

Is there a way to get process ID from which signal came from? Or is there another way to get process ID from which signal came from without blocking main flow of application?

Upvotes: 3

Views: 1781

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148880

You cannot directly. The signal module of Python standard library has no provision for giving access to the Posix sigaction_t structure. If you really need that, you will have to build a Python extension in C or C++.

You will find pointers for that in Extending and Embedding the Python Interpreter - this document should also be available in your Python distribution

Upvotes: 6

dkol
dkol

Reputation: 1469

os.getpid() returns the current process id. So when you send a signal, you can print it out, for example.

import signal
import os
import time

def receive_signal(signum, stack):
    print 'Received:', signum

signal.signal(signal.SIGUSR1, receive_signal)
signal.signal(signal.SIGUSR2, receive_signal)

print 'My PID is:', os.getpid()

Check this for more info on signals.

To send pid to the process one may use Pipe

import os
from multiprocessing import Process, Pipe


def f(conn):
    conn.send([os.getpid()])
    conn.close()

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    print parent_conn.recv()   # prints os.getpid()
    p.join()

Exchanging objects between processes

Upvotes: -2

Related Questions