【发布时间】:2018-04-25 06:40:39
【问题描述】:
我需要在进程之间使用共享内存,我找到了一个示例代码here。首先,我需要学习如何创建一个共享内存块并在其中存储一个字符串。为此,我使用了以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
void* create_shared_memory(size_t size) {
// Our memory buffer will be readable and writable:
int protection = PROT_READ | PROT_WRITE;
// The buffer will be shared (meaning other processes can access it), but
// anonymous (meaning third-party processes cannot obtain an address for it),
// so only this process and its children will be able to use it:
int visibility = MAP_ANONYMOUS | MAP_SHARED;
// The remaining parameters to `mmap()` are not important for this use case,
// but the manpage for `mmap` explains their purpose.
return mmap(NULL, size, protection, visibility, 0, 0);
}
int main() {
char msg[] = "hello world!";
void* shmem = create_shared_memory(1);
printf("sizeof shmem: %lu\n", sizeof(shmem));
printf("sizeof msg: %lu\n", sizeof(msg));
memcpy(shmem, msg, sizeof(msg));
printf("message: %s\n", shmem);
}
输出:
sizeof shmem: 8
sizeof msg: 13
message: hello world!
在主函数中,我正在创建 1 字节 共享内存块 (shmem) 并尝试在其中存储 13 字节 信息 (char msg[])。当我打印出shmem 时,它会打印整个消息。我期待,它只打印出 1 字节 消息,在这种情况下只是 "h"。或者它可能会在编译时给出关于内存大小的错误。
问题是我在这里错过了什么?还是有执行问题? memcpy 在这里重叠吗?感谢您提供任何简短的解释。
提前致谢。
【问题讨论】:
-
底层操作系统机制不对一个字节大小的块进行操作。事实上,您的计算机中几乎没有任何功能。
-
@pvg 那么如果我分配 128 字节并尝试在其中存储 129 字节数据(129 字符),它是如何工作的?它会引发错误吗?
-
@ErselEr 这在
mmap的文档中有所描述,您应该查看该文档。 “如果 offset 或 len 不是 pagesize 的倍数,则映射区域可能会超出指定范围。超出映射对象末尾的任何扩展都将被零填充。” -
我认为你必须用
\0填充共享内存的所有位置