两个进程如何相互通信

时间:2015-01-21 12:36:44

标签: python

我对python很新。 我开始实现twp守护进程,它们将相互发送消息。

现在我只有两个正在运行的守护进程。 我不明白如何建立他们可以通过沟通的东西。 我读到有管道或队列...... sill,无法理解如何构建一个管道或队列,两端将是两个进程..

import multiprocessing
import time
import sys

def daemon():
    p = multiprocessing.current_process()
    print 'Starting:', p.name, p.pid
    sys.stdout.flush()
    while (1):
        time.sleep(1)
    print 'Exiting :', p.name, p.pid
    sys.stdout.flush()

def machine_func():
    p = multiprocessing.current_process()
    print 'Starting:', p.name, p.pid
    sys.stdout.flush()
    while (1):
        time.sleep(1)
    print 'Exiting :', p.name, p.pid
    sys.stdout.flush() 


    cs = multiprocessing.Process(name='control_service',  target=control_service_func)
    cs.daemon = True

    m = multiprocessing.Process(name='machine', target=machine_func)
    m.daemon = True

    cs.start()
    m.start()

2 个答案:

答案 0 :(得分:0)

您可以在此处找到非常好的示例:Communication Between Processes

答案 1 :(得分:0)

您可以通过以下文本文件与守护进程通信:

from multiprocessing import Process
from ast import literal_eval as literal
from random import random
import time

def clock():  # 24 hour clock formatted HH:MM:SS
    return str(time.ctime())[11:19]

def sub_a(): # writes dictionary that tallys +/- every second

    a = 0
    while 1:
        data = {'a': a}
        opened = 0
        while not opened:
            try:
                with open('a_test.txt', 'w+') as file:
                    file.write(str(data))
                    opened = 1
            except:
                print ('b_test.txt in use, try WRITE again...')
                pass
        a+=1
        time.sleep(random()*2)

def sub_b(): # writes dictionary that tallys +/- every 2 seconds

    b = 0
    while 1:
        data = {'b': b}
        opened = 0
        while not opened:
            try:
                with open('b_test.txt', 'w+') as file:
                    file.write(str(data))
                    opened = 1
            except:
                print ('b_test.txt in use, try WRITE again...')
                pass
        b += 1
        time.sleep(random()*4)

# clear communication lines
with open('a_test.txt', 'w+') as file:
    file.write('')
with open('b_test.txt', 'w+') as file:
    file.write('')

# begin daemons
sa = Process(target=sub_a)
sa.daemon = True
sb = Process(target=sub_b)
sb.daemon = True
sa.start()
sb.start()

begin = time.time()
m = 0
while 1:

    m += 1
    time.sleep(1)
    elapsed = int(time.time()-begin)

    #fetch data from deamons
    opened = 0
    while not opened:
        try:
            with open('a_test.txt', 'r') as f:
                a = literal(f.read())
                opened = 1
        except:
            print ('a_test.txt in use, try READ again...')
            pass

    opened = 0
    while not opened:
        try:
            with open('b_test.txt', 'r') as f:
                b = literal(f.read())
                opened = 1
        except:
            print ('READ b_test.txt in use, try READ again...')
            pass
    print(clock(), '========', elapsed, b['b'], a['a'])

以这种方式你可以将对象(如dict)变成string,write()到文件,然后:

ast.literal_eval

当你阅读()

时,将它从另一边拿回来

while not opened try

方法可以防止竞争条件,因此守护进程和主进程有时间在打开/处理/关闭文件时不会发生冲突

with open as file

方法确保文件有效打开和关闭

额外的好处是你可以在编辑器中打开文本文件来实时检查它的状态。