3

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?

dkol
  • 1,421
  • 1
  • 11
  • 19
Ivan Kolesnikov
  • 1,787
  • 1
  • 29
  • 45

2 Answers2

6

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

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
-2

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

dkol
  • 1,421
  • 1
  • 11
  • 19
  • Thanks for the response! But I want identify pid of process which sending signals on receiver side. – Ivan Kolesnikov Oct 21 '15 at 08:38
  • You can use something like `Pipe` then. I will add some code to the answer – dkol Oct 21 '15 at 08:47
  • This does not answer the question. Letting the sender additionally send it's ID via a Pipe kind of makes sending a signal obsolete, because in that case you can just monitor the pipe and do not need any additional signal. – Morty Jul 24 '19 at 10:51