[python]代码库
#python 2
#进程1 server.py
import mmap
import contextlib
import time
# 使用 test.dat 文件来映射内存,分配1024字节的大小,模拟每秒写入最新数据
with open("test.dat", "w") as f:
f.write('x00' * 1024)
with open('test.dat', 'r+') as f:
with contextlib.closing(mmap.mmap(f.fileno(), 1024, access=mmap.ACCESS_WRITE)) as m:
for i in range(1, 10001):
m.seek(0)
s = "msg " + str(i)
s.rjust(1024, 'x00')
m.write(s)
m.flush()
time.sleep(1)
# 进程2 client.py
import mmap
import contextlib
import time
# 从映射文件 test.dat 中加载数据到内存 模拟每秒读取最新数据
while True:
with open('test.dat', 'r') as f:
with contextlib.closing(mmap.mmap(f.fileno(), 1024, access=mmap.ACCESS_READ)) as m:
s = m.read(1024).replace('x00', '')
print s
time.sleep(1)