简体   繁体   English

如何从子进程向父进程发送信号?

[英]How to send signal from subprocess to parent process?

I tried using os.kill but it does not seem to be working.我尝试使用os.kill但它似乎不起作用。

import signal
import os
from time import sleep


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

signal.signal(signal.SIGALRM, isr)

pid = os.fork()
if pid == 0:
    def sisr(signum, frame):        
        os.kill(os.getppid(), signal.SIGALRM)

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

    while True:
        print "2"
else:
    sleep(2)

Your sisr handler never executes.您的sisr处理程序永远不会执行。

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” .该行设置了一个虚拟计时器,根据文档, 仅在进程执行时递减间隔计时器,并在到期时交付 SIGVTALRM”

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.打印在您的进程中几乎不需要任何时间,所有工作都由内核完成,将输出传送到您的控制台应用程序(xterm、konsole 等)和应用程序重新绘制屏幕。 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


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

signal.signal(signal.SIGALRM, isr)

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

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

    while True:
        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.注意:sisr第二次运行sisr时崩溃,因为此时父进程已经退出,所以os.getppid()返回0并且禁止向进程 0 发送信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM