在 android 使用共享buffer 的方法,下面给出一个 goggle 自带的例子
https://android.googlesource.com/platform/system/core/+/master/libcutils/ashmem_test.cpp
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <linux/fs.h>
#include <stdint.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#include <android-base/macros.h>
#include <android-base/unique_fd.h>
#include <cutils/ashmem.h>
#include <gtest/gtest.h>
using android::base::unique_fd;
void TestCreateRegion(size_t size, unique_fd &fd, int prot) {
fd = unique_fd(ashmem_create_region(nullptr, size));
ASSERT_TRUE(fd >= 0);
ASSERT_TRUE(ashmem_valid(fd));
ASSERT_EQ(size, static_cast<size_t>(ashmem_get_size_region(fd)));
ASSERT_EQ(0, ashmem_set_prot_region(fd, prot));
// We've been inconsistent historically about whether or not these file
// descriptors were CLOEXEC. Make sure we're consistent going forward.
// https://issuetracker.google.com/165667331
ASSERT_EQ(FD_CLOEXEC, (fcntl(fd, F_GETFD) & FD_CLOEXEC));
}
void TestMmap(const unique_fd& fd, size_t size, int prot, void** region, off_t off = 0) {
ASSERT_TRUE(fd >= 0);
ASSERT_TRUE(ashmem_valid(fd));
*region = mmap(nullptr, size, prot, MAP_SHARED, fd, off);
ASSERT_NE(MAP_FAILED, *region);
}
void TestProtDenied(const unique_fd &fd, size_t size, int prot) {
ASSERT_TRUE(fd >= 0);
ASSERT_TRUE(ashmem_valid(fd));
EXPECT_EQ(MAP_FAILED, mmap(nullptr, size, prot, MAP_SHARED, fd, 0));
}
void TestProtIs(const unique_fd& fd, int prot) {
ASSERT_TRUE(fd >= 0);
ASSERT_TRUE(ashmem_valid(fd));
EXPECT_EQ(prot, ioctl(fd, ASHMEM_GET_PROT_MASK));
}
void FillData(uint8_t* data, size_t dataLen) {
for (size_t i = 0; i < dataLen; i++) {
data[i] = i & 0xFF;
}
}
TEST(AshmemTest, BasicTest) {
constexpr size_t size = PAGE_SIZE;
uint8_t data[size];
FillData(data, size);
unique_fd fd;
ASSERT_NO_FATAL_FAILURE(TestCreateRegion(size, fd, PROT_READ | PROT_WRITE));
void *region1;
ASSERT_NO_FATAL_FAILURE(TestMmap(fd, size, PROT_READ | PROT_WRITE, ®ion1));
memcpy(region1, &data, size);
ASSERT_EQ(0, memcmp(region1, &data, size));
EXPECT_EQ(0, munmap(region1, size));
void *region2;
ASSERT_NO_FATAL_FAILURE(TestMmap(fd, size, PROT_READ, ®ion2));
ASSERT_EQ(0, memcmp(region2, &data, size));
EXPECT_EQ(0, munmap(region2, size));
}
只需要参考其中 TEST(AshmemTest, BasicTest) 就可以知道其基本的用法