您有多种选择。由于您使用的是 Linux,因此您可以使用 UNIX 域套接字。或者,您可以将数据序列化为 ASCII 或 JSon 或其他格式,并通过管道、SHM(共享内存段)、消息队列、DBUS 或类似的方式提供数据。值得考虑的是您拥有什么类型的数据,因为这些 IPC 机制具有不同的性能特征。有一个USENIX 论文草稿 http://anil.recoil.org/papers/drafts/2012-usenix-ipc-draft1.pdf对各种权衡进行了很好的分析,值得一读。
既然您(在这个答案的评论中)说您更喜欢使用 SHM,那么这里有一些代码示例可以帮助您开始。使用Pythonposix_ipc http://semanchuk.com/philip/posix_ipc/图书馆:
import posix_ipc # POSIX-specific IPC
import mmap # From Python stdlib
class 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 http://basepath.com/aup/jtux/似乎提供了等效的功能,并且您需要的 API 位于UPosixIPC http://basepath.com/aup/jtux/javadoc/jtux/UPosixIPC.html class.
下面的代码概述了您需要实现的事情。然而,有几件事缺失——异常处理是显而易见的,还有一些标志(可以在U常数 http://basepath.com/aup/jtux/javadoc/jtux/UConstant.html),并且您需要添加一个信号量来保护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
/* Lookup flags and perms in your system docs */
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);
}
}