c/linux - ftruncate 和 POSIX 共享内存段 [英] c/linux - ftruncate and POSIX Shared Memory Segments

查看:71
本文介绍了c/linux - ftruncate 和 POSIX 共享内存段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的最终目标是我希望能够扩展共享内存段的大小并通知进程在扩展后重新映射该段.然而,似乎在共享内存 fd 上第二次调用 ftruncate 失败并显示 EINVAL.我能找到的唯一其他问题没有答案:ftruncate 第二次失败

The end goal here is that I'd like to be able to extend the size of a shared memory segment and notify processes to remap the segment after the extension. However it seems that calling ftruncate a second time on a shared memory fd fails with EINVAL. The only other question I could find about this has no answer: ftruncate failed at the second time

ftruncate 和 shm_open 的联机帮助页没有提到不允许在创建后扩展共享内存段,实际上它们似乎表明它们可以通过 ftruncate 调整大小,但到目前为止我的测试表明并非如此.我能想到的唯一解决方案是销毁共享内存段并以更大的大小重新创建它,但是这将需要所有已对该段进行 mmap 的进程在对象被销毁并可用于重新创建之前取消它的映射.

The manpages for ftruncate and shm_open make no mention of disallowing the expansion of shared memory segments after creation, in fact they seem to indicate that they can be resized via ftruncate but so far my testing has shown otherwise. The only solution I can think of would be to destroy the shared memory segment and recreate it at a larger size, however this would require all processes that have mmap'd the segment to unmap it before the object will be destroyed and available for recreation.

有什么想法吗?谢谢!

按照简单示例的要求

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>

int main(int argc, char *argv[]){
    const char * name = "testfile";
    size_t sz = 4096; // page size on my sys
    int fd;
    if((fd = shm_open(name, O_CREAT | O_RDWR, 0666)) == -1){
        perror("shm_open");
        exit(1);
    }
    ftruncate(fd, sz);
    perror("First truncate");
    ftruncate(fd, 2*sz);
    perror("second truncate");

    shm_unlink(name);
    return 0;
}

输出:

First truncate: Undefined error: 0
second truncate: Invalid argument

编辑 - 答案:这似乎是 POSIX 标准的 OSX 实现的一个问题,上面的代码片段适用于 3.13.0-53 通用 GNU/Linux 内核以及我猜想的其他内核.

EDIT - Answer: Appears that this is an issue with OSX implementation of the POSIX standard, the above snippet works on a 3.13.0-53-generic GNU/Linux kernel and likely others I'd guess.

推荐答案

关于你的最终目标,这里是我写的一个开源库,看起来很匹配:rszshm - 可调整大小的指针安全共享内存.

With respect to your end goal, here's an open source library I wrote that seems to be a match: rszshm - resizable pointer-safe shared memory.

这篇关于c/linux - ftruncate 和 POSIX 共享内存段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆