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

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)

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

 

上一篇:王者荣耀背后的实时大数据平台用了什么黑科技?


下一篇:自己动手实现 Shell多进程套套符