共享内存ASharedMemory

2022-05-28  本文已影响0人  赛非斯
/**
 * Create a shared memory region.
 *
 * Create shared memory region and returns an file descriptor.  The resulting file descriptor can be
 * mmap'ed to process memory space with PROT_READ | PROT_WRITE | PROT_EXEC. Access to shared memory
 * region can be restricted with {@link ASharedMemory_setProt}.
 *
 * Use close() to release the shared memory region.
 *
 * Use {@link android.os.ParcelFileDescriptor} to pass the file descriptor to
 * another process. File descriptors may also be sent to other processes over a Unix domain
 * socket with sendmsg and SCM_RIGHTS. See sendmsg(3) and cmsg(3) man pages for more information.
 *
 * If you intend to share this file descriptor with a child process after
 * calling exec(3), note that you will need to use fcntl(2) with FD_SETFD
 * to clear the FD_CLOEXEC flag for this to work on all versions of Android.
 *
 * Available since API level 26.
 *
 * \param name an optional name.
 * \param size size of the shared memory region
 * \return file descriptor that denotes the shared memory; -1 and sets errno on failure, or -EINVAL if the error is that size was 0.
 */
int ASharedMemory_create(const char *name, size_t size) __INTRODUCED_IN(26);

1、消费端

ASharedMemory::ASharedMemory(const char* name,size_t size,void ** outPtr){
    mFd = ASharedMemory_create(name, size);
    const int access =PROT_READ | PROT_WRITE;
    const int flags =MAP_SHARED;
    void *ptr = mmap(NULL,size,access,flags,mFd,0);
    if(ptr==NULL){
        throw runtime_error("failed to create shared memory");
    }
    *outPtr = ptr;
}
void* FileUtil::waitThread(void *ptr){
      struct utils *util = reinterpret_cast<struct utils*>(ptr);
    while (os_thread_helper_is_running(&util->oth)){
        if(ptr!=NULL) {
            LOGE("os_thread_helper_wait_locked");
            os_thread_helper_lock(&util->oth);
            os_thread_helper_wait_locked(&util->oth);
            LOGE("readSharedData mUtil.name = %s ,id= %d", util->name, util->id);
            os_thread_helper_unlock(&util->oth);
        }
    }
}

2、生产端

上一篇 下一篇

猜你喜欢

热点阅读