你有很多选择。因为您使用的是Linux,所以可以使用UNIX域套接字。或者,可以将数据序列化为ASCII或JSon或其他格式,并通过管道、SHM(共享内存段)、消息队列、dbu或类似的格式提供数据。值得考虑的是您拥有哪种类型的数据,因为这些IPC机制具有不同的性能特征。这里有一个draft USENIX paper很好地分析了各种权衡,值得一读。
既然您在对这个答案的注释中说您更喜欢使用SHM,那么下面是一些代码示例。使用Pythonposix_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中所说的似乎提供了等效的功能,而且您需要的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
/* 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);
}
}