首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >两个进程如何相互通信

两个进程如何相互通信
EN

Stack Overflow用户
提问于 2015-01-21 20:36:44
回答 2查看 362关注 0票数 1

我是python的新手。我开始实现相互发送消息的twp守护进程。

现在我只有2个守护进程在运行。我不知道如何建立他们可以交流的东西..我读到有管道,或队列...看不懂如何搭建管道或队列,即两端将是两个进程..

代码语言:javascript
复制
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()
EN

回答 2

Stack Overflow用户

发布于 2015-01-21 20:48:28

你可以在这里找到非常好的例子:Communication Between Processes

票数 0
EN

Stack Overflow用户

发布于 2018-03-22 08:07:49

您可以通过如下文本文件与后台进程进行通信:

代码语言:javascript
复制
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)转换为字符串,将()写入文件,然后:

ast.literal_eval

当你读()的时候,把它放回另一边。

while not opened try

方法可以防止争用情况,以便守护进程和主进程在打开/进程/关闭文件时有时间不发生冲突。

with open as file

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

附加的好处是您可以在编辑器中打开文本文件,以实时检查其状态。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28067436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档