如何使用共享内存(IPC)的安卓如何使用、内存、IPC

2023-09-06 18:44:21 作者:深井冰

我已经写在Linux的一个简单的共享内存的C程序。 如何使用共享内存(或者我应该称之为ashmem?)的机器人? 我希望你能给我一步一步的指导。

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.

推荐答案

一个过程,下面的步骤创建一个新的ashmem面积:

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

(1)打开设备文件,为/ dev / ashmem,并获得文件描述符。 (2)调用ASHMEM_SET_NAME的ioctl设置ashmem名。这似乎是虚拟设备文件,因此,如果您将其命名为my_mem文件名更改为为/ dev / ashmem / my_mem。 (3)调用ASHMEM_SET_SIZE的ioctl设置ashmem大小,以字节为单位。

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

该cutils库有一个函数ashmem_create_region这些步骤,包装成一个函数调用:

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);

文件描述符可以与其他进程共享。 Android提供了一种特殊的方式来分享表兄弟进程之间的文件描述符,用所谓的粘合剂其他服务。然后,每个进程mmaps文件:

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.