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.
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.
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.
Use binder IPC in Android. I think the binder uses the kernel memory, which is shared across all process, for Inter process communication.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.