【发布时间】:2020-09-20 19:06:31
【问题描述】:
我有一个使用shm_open/ftruncate/mmap 分配内存的演示程序:
#include <unistd.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
void shm_alloc(const char* path, size_t size) {
int shmfd = shm_open(path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0666);
if (shmfd == -1) {
perror("shm_open");
exit(1);
}
printf("shm_open success, path: %s, fd: %d\n", path, shmfd);
int ret = ftruncate(shmfd, size);
if (ret != 0) {
perror("ftruncate");
exit(1);
}
printf("ftruncate success, fd: %d, size: %#lx\n", shmfd, size);
void* addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
if (addr == MAP_FAILED) {
perror("mmap");
exit(1);
}
printf("mmap success, fd: %d, size: %#lx, addr: %p\n", shmfd, size, addr);
close(shmfd);
memset(addr, 0x00, size); // <===== Crashes here
printf("memset success, size: %#lx, addr: %p\n", size, addr);
}
int main() {
shm_alloc("/a", 0x100000000); // 4GB
shm_alloc("/b", 0x100000000); // 4GB, crashes at the `memset` in this call
return 0;
}
程序创建两个 4GB 共享内存区域和memset 它们。运行程序它输出以下内容然后崩溃:
shm_open success, path: /a, fd: 3
ftruncate success, fd: 3, size: 0x100000000
mmap success, fd: 3, size: 0x100000000, addr: 0x7f4c15625000
memset success, size: 0x100000000, addr: 0x7f4c15625000
shm_open success, path: /b, fd: 3
ftruncate success, fd: 3, size: 0x100000000
mmap success, fd: 3, size: 0x100000000, addr: 0x7f4b15625000
[1] 1250849 bus error (core dumped) ./a.out
如您所见,第一个memset 成功,第二个崩溃,我gdbed 程序,它显示第二个区域mmaped 0x7f4b15625000 没有足够的空间( 4GB)(在gdb中执行p (char*)addr + 0xFFFFFFFF会产生Cannot access memory错误),但它确实有小于4GB的空间(可能是2GB或3GB,我没有测试准确的大小)。
我在 Debian 9 上运行,物理内存为 16GB,没有交换空间,所以这似乎不是内存不足的问题,有人知道吗?我不应该相信ftruncate/mmap 电话吗?
编辑:运行df -h 显示/dev/shm 的大小为7.8G,因此它可能是根本原因。但是,为什么即使/dev/shm 没有足够的空间,ftruncate 也会成功?为什么当我ls -alh /dev/shm 时,它会显示两个文件“a”和“b”,大小均为 4.0GB?
free -h 的输出:
# before running the program:
total used free shared buff/cache available
Mem: 15G 701M 9.0G 161M 5.7G 14G
Swap: 0B 0B 0B
# after running the program:
total used free shared buff/cache available
Mem: 15G 702M 1.4G 7.8G 13G 6.6G
Swap: 0B 0B 0B
ulimit -a 的输出:
-t: cpu time (seconds) unlimited
-f: file size (blocks) unlimited
-d: data seg size (kbytes) unlimited
-s: stack size (kbytes) 8192
-c: core file size (blocks) unlimited
-m: resident set size (kbytes) unlimited
-u: processes 65535
-n: file descriptors 1024768
-l: locked-in-memory size (kbytes) 64
-v: address space (kbytes) unlimited
-x: file locks unlimited
-i: pending signals 63053
-q: bytes in POSIX msg queues 819200
-e: max nice 0
-r: max rt priority 0
-N 15: unlimited
【问题讨论】:
-
请发布
df -h的输出以及任何可能与此错误相关的系统日志消息。 -
运行
ulimit -a,看看内存大小是否有限制。 -
对不起,我的意思是
free -h。 -
@pifor 请看我的编辑。
-
@MaximEgorushkin 请看我的编辑。
标签: c linux shared-memory mmap