Python 从正在运行的进程调用函数

Python 从正在运行的进程调用函数,python,ipc,subprocess,Python,Ipc,Subprocess,我的程序启动一个子进程,在初始化后必须向父进程发送某种信号。如果我能在父级中设置一个处理程序,它将在发送此信号时被调用。有什么办法吗 Alendit您可以使用Python标准库中的来注册信号处理程序。然后,子流程将使用正常的信号发送机制。父代码: 子代码: 注意这种形式的IPC,因为它有它的问题,例如: 在原始Unix系统中,当 使用 该信号由 信号的传递、处置 信号的频率将重置为 SIG_DFL,系统没有 阻止进一步实例的交付 信号的一部分。系统V还提供 这些语义表示信号。这 是坏的,因为

我的程序启动一个子进程,在初始化后必须向父进程发送某种信号。如果我能在父级中设置一个处理程序,它将在发送此信号时被调用。有什么办法吗

Alendit

您可以使用Python标准库中的来注册信号处理程序。然后,子流程将使用正常的信号发送机制。

父代码:

子代码:

注意这种形式的IPC,因为它有它的问题,例如:

在原始Unix系统中,当 使用 该信号由 信号的传递、处置 信号的频率将重置为 SIG_DFL,系统没有 阻止进一步实例的交付 信号的一部分。系统V还提供 这些语义表示信号。这 是坏的,因为信号可能是 在处理程序之前再次交付 有机会重建自己。 此外,快速交付 相同的信号可能导致递归 处理程序的调用


我建议您阅读整个手册页。

如果您使用的是Python 2.6,您可以使用标准库中的多处理模块,特别是管道和队列。文档中的简单示例:

from multiprocessing import Process, Pipe

def f(conn): #This code will be spawned as a new child process
    conn.send([42, None, 'hello']) #The child process sends a msg to the pipe
    conn.close()

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,)) # prepare to spawn the child
    p.start() # spawn it
    print parent_conn.recv()   # prints "[42, None, 'hello']"
    p.join() #wait for child to exit

如果您使用的是python2.4或2.5,请不要失望-有一个后端口可用。

如果有办法将参数发送到父函数,您的解决方案将非常好。非常感谢,首先我有点害怕,因为事实上我必须使用python2.5,但后端口工作得很好。
import os
import signal

signal.kill(os.getppid(), signal.SIGUSR1)
from multiprocessing import Process, Pipe

def f(conn): #This code will be spawned as a new child process
    conn.send([42, None, 'hello']) #The child process sends a msg to the pipe
    conn.close()

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,)) # prepare to spawn the child
    p.start() # spawn it
    print parent_conn.recv()   # prints "[42, None, 'hello']"
    p.join() #wait for child to exit