Reputation: 744
My main process spawns a new process, this new process needs to terminate if SIGTERM/SIGKILL signal is sent to it. I am new to python and I don't know how to pass this signal as argument to the function.
My code is:
import os
import random
import time
import sys
import multiprocessing as mp
import psutil
import signal
def info(title):
print (title)
print ('module name:', __name__)
if hasattr(os, 'getppid'):
print ('parent process:', os.getppid())
print ('process id:', os.getpid())
def foo(q,num):
info('function foo')
if type(num) is int:
num*=2
q.put(num)
elif type(num) is Signal:
print ("Terminated")
time.sleep(10)
os.kill(os.getpgid(pid), num)
else :
sys.exit("error")
def receive_signal(signum, stack):
print 'Received:', signum
if __name__ == '__main__':
info ("main")
#mp.set_default('spawn')
number = random.randint(0,100)
print ("Initial number: ",number)
q = mp.Queue()
p = mp.Process(target=foo, args=(q,number))
p.start()
print ("Final Number: ",(q.get()))
foo(q,signal.signal(signal.SIGTERM,recieve_signal))
p.join()
At this moment I am struck at signal passing to function foo(q,signal.signal(signal.SIGTERM,recieve_signal))
Any help is much appreciated
Upvotes: 0
Views: 2265
Reputation: 3206
As per documentation, signal.signal(...)
only registers a signal, but it doesn't return any value and None
gets passed to your foo()
function:
foo(q,signal.signal(signal.SIGTERM,recieve_signal))
On the other hand, the second parameter to signal.signal()
is a callback that is invoked when a signal of a specific type is caught (signal.SIGTERM
in your case). You have already defined such handler, it's the receive_signal()
function and its first parameter is the signal number. You can pass this to your foo()
function by simply calling it:
def receive_signal(signum, stack):
print 'Received:', signum
foo(q, signum) # NOTE: q is a module-level variable here
Upvotes: 1