通过命令管道,在进程之间进行通信的简单例子

本文提供了两个Python脚本示例,展示如何使用命名管道(FIFO)进行进程间通信。一个脚本负责写入消息到命名管道,另一个则读取并打印这些消息。通过这种方式,文章介绍了基本的IPC机制。

write_to_named_pipe.py

import os


if __name__ == "__main__":
    named_pipe = "my_pipe"

    if not os.path.exists(named_pipe):
        os.mkfifo(named_pipe)

    def write_message(input_pipe, message):
        fd = os.open(input_pipe, os.O_WRONLY)
        os.write(fd, (message +  str(os.getpid())))
        os.close(fd)
    write_message(named_pipe, "from write_pipe...")

  

read_from_named_pipe.py

import os

if __name__ == "__main__":
    named_pipe = "my_pipe"
    def read_message(input_pipe):
        fd = os.open(input_pipe, os.O_RDONLY)
        message = ("I pid [%d] received a message => %s" %(os.getpid(), os.read(fd, 22)))
        os.close(fd)
        return message
    print read_message(named_pipe)

  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值