標籤:例子 部落格 tty map 具體細節 地址 int 實現 進程地址空間
前一篇部落格說了怎樣通過具名管道實現處理序間通訊,但是要在windows是使用具名管道,需要使用python調研windows api,太麻煩,於是想到是不是可以通過共用記憶體的方式來實現。查了一下,Python中可以使用mmap模組來實現這一功能。
Python中的mmap模組是通過映射同一個普通檔案實現共用記憶體的。檔案被映射到進程地址空間後,進程可以像訪問記憶體一樣對檔案進行訪問。
不過,mmap在linux和windows上的API有些許的不一樣,具體細節可以查看mmap的文檔。
下面看一個例子:
server.py
這個程式使用 test.dat 檔案來映射記憶體,並且分配了1024位元組的大小,每隔一秒更新一下記憶體資訊。
import mmapimport contextlibimport timewith 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)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
client.py
這個程式從上面映射的檔案 test.dat 中載入資料到記憶體中。
import mmapimport contextlibimport timewhile 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)
上面的代碼可以在linux和windows上運行,因為我們明確指定了使用 test.dat 檔案來映射記憶體。如果我們只需要在windows上實現共用記憶體,可以不用指定使用的檔案,而是通過指定一個tagname來標識,所以可以簡化上面的代碼。如下:
server.py
import mmapimport contextlibimport timewith contextlib.closing(mmap.mmap(-1, 1024, tagname=‘test‘, access=mmap.ACCESS_WRITE)) as m: for i in range(1, 10001): m.seek(0) m.write("msg " + str(i)) m.flush() time.sleep(1)
client.py
import mmapimport contextlibimport timewhile True: with contextlib.closing(mmap.mmap(-1, 1024, tagname=‘test‘, access=mmap.ACCESS_READ)) as m: s = m.read(1024).replace(‘\x00‘, ‘‘) print s time.sleep(1)
Python處理序間通訊之共用記憶體