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.
4 Answers
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.

- 4,431
- 35
- 29
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.

- 489
- 3
- 5
-
I'm back again man... Using AOSP, I have made a "Hello World" C program that can be run natively in Android. I wanted to make that "Hello World" program to have an ashmem capability. Is it possible? – Jun 27 '13 at 06:54
Use binder IPC in Android. I think the binder uses the kernel memory, which is shared across all process, for Inter process communication.

- 732
- 3
- 13
-
Binder is limited to [transactions of 1 Mb or less](https://developer.android.com/reference/android/os/TransactionTooLargeException), so if you need larger, `ashmem` is the way to go. – Jk Jensen Jan 22 '19 at 17:41
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.

- 18,356
- 16
- 68
- 108