如何使用pyzmq在父进程和子进程之间进行通信?

时间:2019-01-10 12:28:22

标签: python multiprocessing parent-child zeromq pyzmq

我正在使用python多重处理创建子进程。父级将创建一个套接字为zmq.PUB。子级将订阅该套接字。但是问题是孩子没有收到任何消息。

此代码在Windows中运行。但是,当我尝试使用RHEL 7.5时,它不起作用。

import multiprocessing
import zmq
import os
import time

port = '5555'


def child():
    print("Child pid: ", os.getpid())
    context = zmq.Context.instance()
    socket = context.socket(zmq.SUB)
    socket.setsockopt(zmq.SUBSCRIBE, str.encode(''))
    socket.connect("tcp://localhost:%s" % port)
    poller = zmq.Poller()
    poller.register(socket, zmq.POLLIN)
    socks = dict(poller.poll())
    while (True):
        for key, value in socks.items():
            print(key, " ", value)
        time.sleep(5)
        print('receiving data')
        if socket in socks and socks[socket] == zmq.POLLIN:
            try:
                string = socket.recv_string(flags=zmq.NOBLOCK)
            except (zmq.error.Again, Exception) as e:
                break
        print('data received: ', string)


def main():
    print("Parent pid: ", os.getpid())
    context = zmq.Context.instance()
    socket = context.socket(zmq.PUB)
    socket.bind("tcp://*:%s" % port)
    childproc = multiprocessing.Process(name='childproc',target=child)
    childproc.daemon = False
    childproc.start()
    while (True):
        print('data publishing')
        socket.send_string("hello")
        time.sleep(5)

在Windows中,结果为:

Parent pid:  5536
data publishing
Child pid:  13964
data publishing
<zmq.sugar.socket.Socket object at 0x000001E5BB6B3BA8>   1
data publishing
receiving data
data received:  hello
<zmq.sugar.socket.Socket object at 0x000001E5BB6B3BA8>   1
data publishing
receiving data
data received:  hello
......
......
在Linux中,输出为:
Parent pid:  21850
data publishing
Child pid:  21854
data publishing
data publishing
data publishing
data publishing
data publishing
data publishing
data publishing
..........
..........
使用PUB / SUB是否有问题? 我如何使用ZMQ进行此家长与孩子之间的交流? 如果ZMQ不支持此功能,则可以使用哪个其他库? 如果我使用多处理模块中的队列和管道,则可能出现什么问题,如果消息是JSON对象?

0 个答案:

没有答案