How to use Shared Memory (IPC) in Android

痴心易碎 提交于 2019-11-27 02:26:01

问题


I've already written a simple Shared Memory C program in Linux.
How can I use Shared Memory (or should I call it "ashmem?") in Android?

I hope you can give me a step-by-step guide.


回答1:


Here is what worked for me:
1) Open a MemoryFile object: mFile;
2) create a service to map it to ashem using mmap;
3) Return the native file descriptor (fd) to client that binds to your service using ParcelFileDescriptor pfd;
4) Create JNI for the client that takes the fd and map to ashes using mmap;
5) Create InputStream using this fd and now the client can read/write the same memory area using InputStream object.
This link shows how to map a MemoryFile to ashem. This link shows how to send native file descriptor (fd) to client through AIDL and ParcelFileDescriptor to client.

On the server side, you will need create:
1) A service & AIDL that passes native fd to client through ParcelFileDescriptor; 2) A JNI on the service side that does the mapping.

On the client: 1) Methods to Bind to service and then call service to get native fd; 2) A JNI that maps the fd to ashem.

The mapped memory region can then be read/write by the service & client.




回答2:


A process creates a new ashmem area with the following steps:

(1) Open the device file, “/dev/ashmem” and get the file descriptor. (2) Call the ASHMEM_SET_NAME ioctl to set the ashmem name. It appears to be the virtual device file, so if you name it “my_mem” the file name changes to “/dev/ashmem/my_mem”. (3) Call the ASHMEM_SET_SIZE ioctl to set the ashmem size, in bytes.

The cutils library has a function “ashmem_create_region” which wraps up these steps into a single function call:

int fd = ashmem_create_region("my_mem", PAGE_SIZE * 20);

The file descriptor can be shared with other processes. Android provides a special way to share file descriptors between cousin-processes, using another service called “binder”. Then each process mmaps the file:

char *map = mmap(NULL, PAGE_SIZE * 20, PROT_READ|PROT_WRITE,
                                       MAP_SHARED, fd, 0);

and, voila! Instant shared memory.




回答3:


Use binder IPC in Android. I think the binder uses the kernel memory, which is shared across all process, for Inter process communication.




回答4:


Well, if you want to use shared memory API's here is a solution https://github.com/pelya/android-shmem

Like a magic, it works perfectly. You can use shared memory in android across independent processes using shmget(), shmat() and shmdt() API's seamlessly. Give it a try.



来源:https://stackoverflow.com/questions/16099904/how-to-use-shared-memory-ipc-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!