Skip to content Skip to sidebar Skip to footer

How To Send Signal From Subprocess To Parent Process?

I tried using os.kill but it does not seem to be working. import signal import os from time import sleep def isr(signum, frame): print 'Hey, I'm the ISR!' signal.signal(sign

Solution 1:

Your sisr handler never executes.

signal.setitimer(signal.ITIMER_VIRTUAL, 1, 1)

This line sets a virtual timer, which, according to documentation, “Decrements interval timer only when the process is executing, and delivers SIGVTALRM upon expiration”.

The thing is, your process is almost never executing. The prints take almost no time inside your process, all the work is done by the kernel delivering the output to your console application (xterm, konsole, …) and the application repainting the screen. Meanwhile, your child process is asleep, and the timer does not run.

Change it with a real timer, it works :)

import signal
import os
from time import sleep


defisr(signum, frame):
    print"Hey, I'm the ISR!"

signal.signal(signal.SIGALRM, isr)

pid = os.fork()
if pid == 0:
    defsisr(signum, frame):        
        print"Child running sisr"
        os.kill(os.getppid(), signal.SIGALRM)

    signal.signal(signal.SIGALRM, sisr)
    signal.setitimer(signal.ITIMER_REAL, 1, 1)

    whileTrue:
        print"2"
        sleep(1)
else:
    sleep(10)
    print"Parent quitting"

Output:

spectras@etherbee:~/temp$ python test.py
2
Child running sisr    
2
Hey, I'm the ISR!
Parent quitting
spectras@etherbee:~/temp$ Child running sisr

Traceback (most recent call last):
  File "test.py", line 22, in <module>
    sleep(1)
  File "test.py", line 15, in sisr
    os.kill(os.getppid(), signal.SIGALRM)
OSError: [Errno 1] Operation not permitted

Note: the child crashes the second time it runs sisr, because then the parent has exited, so os.getppid() return 0 and sending a signal to process 0 is forbidden.

Post a Comment for "How To Send Signal From Subprocess To Parent Process?"