How to use Shared Memory (IPC) in Android

17,819

Solution 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.

Solution 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.

Share:
17,819
Admin
Author by

Admin

Updated on June 13, 2022

Comments

  • Admin
    Admin almost 2 years

    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.