简体   繁体   中英

Python 2 process communicate on socket

I need 2 processes to communicate. Either may run alone, but when they are running together they should be communicating. They only send a few bytes to each other every minute. Neither is thought of as "host" or "client".

I tried to make a class which handles that in the background. For instance, it first tries to connect to the socket, if that fails it tries to listen, etc. When one program terminates the other takes over listening, etc. After struggling with this for too long I've given up. There are far too many bugs and I can't make it work reliably.

So I am wondering if there is a good alternate solution, or if there is a robust implementation of this sort of thing I can use. I don't have time to fool around any more. I need it to work on windows and linux.

使用0mq和两对PUB / SUB套接字。

If you're having problems with sockets, you might want to look at alternative IPC mechanisms. For example, named pipes let two process to communicate as if they were just writing/readig to/from a file.

The following example shows how a named pipe is created and how to open for reading and writing in two different processes:

import os

pipe_name = '/tmp/ipc'

if not os.path.exists(pipe_name):
    os.mkfifo(pipe_name)
    try:
        with open(pipe_name) as f:
            print 'Received:', f.read()
        with open(pipe_name, 'w') as f:
            message = 'Goodbye World!'
            print 'Sending:', message
            f.write(message)
    finally:
        os.remove(pipe_name)
else:
    with open(pipe_name, 'w') as f:
        message = 'Hello World!'
        print 'Sending:', message
        f.write(message)
    with open(pipe_name) as f:
        print 'Received:', f.read()

The first process will:

  • Create the named pipe
  • Receive a message
  • Send another message
  • Delete the pipe

while the seconde process will just:

  • Send a message
  • Receive another message

If you execute the example above in two different terminals, in the first one you'll get:

Received: Hello World!
Sending: Goodbye World!

and in the second one:

Sending: Hello World!
Received: Goodbye World!

Note: This is just an example. If you need bidirectional communication it would be more convenient to use two named pipes instead of opening just one for reading/writing when you need to receive/send messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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