Writing in ashmem / why is an android an ashtray free?

I want to share data between two (ndk-) processes. For this I use ashmem using this one. One process reads continuously ( read_mem), and one process writes once ( write_mem).

The problem is that the read process does not get the value of the record.

AND

Watching the reader’s cards, I found that android deletes the shared memory file immediately after ashmem_create_region.


read_mem.c

// read_mem.c
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>
#include "ashmem.h"

#define SHM_NAME "test_mem"
int main(int argc, char **argv) {
    int shID = ashmem_create_region(SHM_NAME, 2);
    if (shID < 0)
    {
        perror("ashmem_create_region failed\n");
        return 1;
    }
    // right here /dev/ashmem/test_mem is deleted
    printf("ashmem_create_region: %d\n", shID);
    char *sh_buffer = (char*)mmap(NULL, 2, PROT_READ | PROT_WRITE, MAP_SHARED, shID, 0);
    if (sh_buffer == (char*)-1)
    {
        perror("mmap failed");
        return 1;
    }
    printf("PID=%d", getpid());
    do
    {
        printf("VALUE = 0x%x\n", sh_buffer[0]);
    }
    while (getchar());
    return 0;
}

write_mem.c

// write_mem.c
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>
#include "ashmem.h"

#define SHM_NAME "test_mem"
int main(int argc, char **argv) {
    int shID = ashmem_create_region(SHM_NAME, 2);
    if (shID < 0)
    {
        perror("ashmem_create_region failed\n");
        return 1;
    }
    printf("ashmem_create_region: %d\n", shID);
    char *sh_buffer = (char*)mmap(NULL, 2, PROT_READ | PROT_WRITE, MAP_SHARED, shID, 0);
    if (sh_buffer == (char*)-1)
    {
        perror("mmap failed");
        return 1;
    }
    printf("PID=%d\n", getpid());
    int ch = getchar();
    sh_buffer[0] = ch;
    printf("Written 0x%x\n", ch);
    munmap(sh_buffer, 2);
    close(shID);
    return 0;
}

This is the result:
Reading

130|shell@mako:/data/local/tmp $ ./read_mem
ashmem_create_region: 3
PID=29655
VALUE = 0x0

Record

shell@mako:/data/local/tmp $ ./write_mem
ashmem_create_region: 3
PID=29691
A
Written 0x41

Repeat reading VALUE = 0x0(by pressing the return button)

View reader cards:

shell@mako:/ $ cat /proc/29655/maps | grep test_mem
b6ef5000-b6ef6000 rw-s 00000000 00:04 116213     /dev/ashmem/test_mem (deleted)

as you can see test_memdeleted WHILE read_mem still alive.


Other information

android ndk-build
: LG Nexus 4 (AOSP Lollypop)
/dev/ashmem, .
ashmem,

+4
1

Ashmem Linux, .

-, "()", , ashmem . , /dev/ashmem/ , , i- node , .

, "/dev/ashmem/<name> (deleted)", i- node , , . /dev/ashmem/, , - .

ashmem . "" .

i- node , . , , - , ​​. SysV ( ! - , Android).

, , . :

1) .

2) .

- ( ), Android.

sendmsg() recvmsg() Unix- . , , , SendFd() ReceiveFd() NDK:

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

Voila, ,

+12

Source: https://habr.com/ru/post/1570443/


All Articles