Skip to main content
 首页 » 编程设计

python之如何将信号从子进程发送到父进程

2024年10月17日11myhome

我尝试使用 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) 

请您参考如下方法:

您的 sisr 处理程序永远不会执行。

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

此行设置了一个虚拟计时器,根据文档,“仅在进程执行时递减间隔计时器,并在到期时发送 SIGVTALRM”。 p>

问题是,您的进程几乎从不执行。在你的进程中打印几乎不需要时间,所有的工作都是由内核完成的,将输出传递给你的控制台应用程序(xterm,konsole,......)和应用程序重新绘制屏幕。同时,您的子进程处于休眠状态,计时器不运行。

用一个真正的计时器改变它,它有效:)

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" 

输出:

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 

注意子进程在第二次运行sisr时崩溃,因为那时父进程已经退出,所以os.getppid () 返回 0 并禁止向进程 0 发送信号。