Writing to ashmem / why does android free ashmem?

后端 未结 1 1194
情歌与酒
情歌与酒 2020-12-10 07:16

I want to share data between two (ndk-)processes. For this I use ashmem using this source.
One process is continuously reading (read_mem) and one process is

相关标签:
1条回答
  • 2020-12-10 07:56

    Ashmem doesn't work like regular shared memory on Linux, and there is a good reason for it.

    First, let's try to explain the "(deleted)" part, this is an implementation detail of how ashmem is implemented in the kernel. What it really means is that a file entry was created in the /dev/ashmem/ directory, then later removed, but that the corresponding i-node still exists because there is at least one open file-descriptor for it.

    You could actually create several ashmem regions with the same name, and they would all appear as "/dev/ashmem/<name> (deleted)", but each one of them would correspond to a different i-node, and thus a different memory region. And if you look under /dev/ashmem/ you would see that the directory is still empty.

    That's why the name of an ashmem region is really only used for debugging. There is no way to 'open' an existing region by name.

    An ashmem i-node, and corresponding memory, is automatically reclaimed when the last file descriptor to it is closed. This is useful because it means that if your process dies due to a crash, the memory will be reclaimed by the kernel automatically. This is not the case with regular SysV shared memory (a crashing process just leaks the memory! Something unacceptable on an embedded system like Android).

    Your test programs create two distinct ashmem regions with the same name, that's why they dont work as you think they should. What you need instead is:

    1) Create a single ashmem region in one of the process.

    2) Pass a new file descriptor to the region from the first process to the second one.

    One way to do that is to fork the first process to create the second (this will automatically duplicate the file descriptors), but this is generally not a good idea under Android.

    A better alternative is to use sendmsg() and recvmsg() to send the file descriptor through a Unix-domain socket between the two processes. This is generally tricky, but as an example, have a look at the SendFd() and ReceiveFd() functions in the following source file was written for the NDK:

    https://android.googlesource.com/platform/ndk/+/android-5.0.0_r7/sources/android/crazy_linker/tests/test_util.h

    Voila, hope this helps

    0 讨论(0)
提交回复
热议问题