您有很多选择。由于您使用的是Linux,因此可以使用UNIX域套接字。或者,您可以将数据序列化为ASCII或JSon或其他某种格式,然后通过管道,SHM(共享内存段),消息队列,DBUS或类似内容将其送入。值得考虑一下您拥有哪种数据,因为这些IPC机制具有不同的性能特征。USENIX的草稿草案对各种折衷进行了很好的分析,值得一读。
由于您说(在此答案的注释中)说您更喜欢使用SHM,因此这里有一些代码示例可以帮助您入门。使用Python
posix_ipc库:
import posix_ipc # POSIX-specific IPCimport mmap # From Python stdlibclass SharedMemory(object): """Python interface to shared memory. The create argument tells the object to create a new SHM object, rather than attaching to an existing one. """ def __init__(self, name, size=posix_ipc.PAGE_SIZE, create=True): self.name = name self.size = size if create: memory = posix_ipc.SharedMemory(self.name, posix_ipc.O_CREX,size=self.size) else: memory = posix_ipc.SharedMemory(self.name) self.mapfile = mmap.mmap(memory.fd, memory.size) os.close(memory.fd) return def put(self, item): """Put item in shared memory. """ # TODO: Deal with the case where len(item) > size(self.mapfile) # TODO: Guard this method with a named semaphore self.mapfile.seek(0) pickle.dump(item, self.mapfile, protocol=2) return def get(self): """Get a Python object from shared memory. """ # TODO: Deal with the case where len(item) > size(self.mapfile) # TODO: Guard this method with a named semaphore self.mapfile.seek(0) return pickle.load(self.mapfile) def __del__(self): try: self.mapfile.close() memory = posix_ipc.SharedMemory(self.name) memory.unlink() except: pass return
对于Java端,您想创建相同的类,尽管我在评论中说过,JTux似乎提供了等效的功能,并且您需要的API在UPosixIPC类中。
下面的代码概述了您需要实现的东西。但是,缺少一些东西-
异常处理是显而易见的东西,还有一些标志(在UConstant中找到它们),并且您需要添加一个信号量来保护
put/
get方法。但是,这应该可以使您走上正确的道路。请记住,一个
mmap或内存映射文件是一段RAM的类似文件的接口。因此,您可以像使用
fd普通文件一样使用其文件描述符。
import jtux.*;class SHM { private String name; private int size; private long semaphore; private long mapfile; // File descriptor for mmap file public SHM(String name, int size, boolean create, int flags, int perms) { this.name = name; this.size = size; int shm; if (create) { flags = flags | UConstant.O_CREAT; shm = UPosixIPC.shm_open(name, flags, UConstant.O_RDWR); } else { shm = UPosixIPC.shm_open(name, flags, UConstant.O_RDWR); } this.mapfile = UPosixIPC.mmap(..., this.size, ..., flags, shm, 0); return; } public void put(String item) { UFile.lseek(this.mapfile(this.mapfile, 0, 0)); UFile.write(item.getBytes(), this.mapfile); return; } public String get() { UFile.lseek(this.mapfile(this.mapfile, 0, 0)); byte[] buffer = new byte[this.size]; UFile.read(this.mapfile, buffer, buffer.length); return new String(buffer); } public void finalize() { UPosix.shm_unlink(this.name); UPosix.munmap(this.mapfile, this.size); }}


