共享内存:
服务端:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ctypes import *
import time
import json
import mmap
import contextlib
import os
SHM_SIZE = 32
send_data = "sensor1"
while True:
with open("shared_memory", "w") as f:
f.write('\x00' * SHM_SIZE)
f.close()
with open("shared_memory", "r+") as f:
with contextlib.closing(mmap.mmap(f.fileno(), SHM_SIZE, access=mmap.ACCESS_WRITE)) as m:
# ss = json.dumps(send_data).rjust(SHM_SIZE-1, '\x00')
ss = json.dumps(send_data)
m.write(ss.encode())
m.flush()
print(json.dumps(send_data).encode())
time.sleep(1)
m.close()
f.close()
客户端:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ctypes import *
import time
import json
import mmap
import contextlib
SHM_SIZE = 32
while True:
with open("shared_memory", "r") as f:
with contextlib.closing(mmap.mmap(f.fileno(), SHM_SIZE, access=mmap.ACCESS_READ)) as m:
s = m.read(SHM_SIZE).replace(b'\x00', b"")
print(s)
time.sleep(1)
m.close()
f.close()