Welcome, guest | Sign In | My Account | Store | Cart

The recipe is an extremely simple demonstration of how two processes can talk to each other using mmap.

Python, 35 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File: mm0.py / mm1.py
#Jerol Harrington, May 10, 2005
# adapted from Fredrik Lundh's Python Standard Library
# This shows how two processes can talk to another using mmap.

import mmap
import os
import time

filename = "sample.txt"

file = open(filename, "r+")
size = os.path.getsize(filename)

data = mmap.mmap(file.fileno(), size)
while True:
    if data[0] == "G":
        print "Process 0 = Go"
        data[1]="S"
    else:
        print "Process 0 = Stop"
        data[1]="G"
    time.sleep(2)

#for the 2nd file, mm1.py, replace the while loop with
#the following:

#while True:
#    if data[1] == "G":
#        print "Process 1 = Go"
#        data[0]="G"
#    else:
#        print "Process 1 = Stop"
#        data[0]="S"
#    time.sleep(2)

I need a simple way to communicate with a process in a Windows environment. Windows is deficient in this respect, compared to Unix or linux. I looked for recipes on the web, but about all I found were examples in Fredrik Lundh's Python Standard Library, and Alex's Nutshell book. The example in Python in a Nutshell works, and I learned a lot by playing with it. However, if you try to enter a string to the physical file that is shorter than the previous one, interesting results ensue.

Create mm0.py and mm1.py, start them in separate shells, and see what happens. Stop one process and see what happens in the other. I think that it is rather cute, but then I am easily amused. Don't forget to create a samples.txt with some data in it.

1 comment

Jerry Rocteur 13 years, 8 months ago  # | flag

I like this one, I had a lot of fun playing with it.

I'm going to see how many other ways there are for processes to talk to each other in Python.

(I'm still learning)