ftruncate not working on POSIX shared memory in Mac OS X

不羁的心 提交于 2019-12-19 02:07:34

问题


I have written a code on Mac OS X to use POSIX shared memory as shown below:

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

int main() {
    int fileHandle = shm_open("TW_ShMem1",O_CREAT|O_RDWR, 0666);

    if(fileHandle==-1) {
       //error.

    } else {
        //Here, it is failing on Mac OS X
        if(-1==ftruncate(fileHandle, 8192)) {
            shm_unlink("TW_ShMem1");
            fileHandle = -1;
        } else {
            return 0;
        }
    }

    return 1;
}

ftruncate on Linux is working without any problem. On Mac OS X, it is returning -1 and errno is EINVAL (as seen in the debugger).

Why is it failing? What is being missed here?


回答1:


This looks like OSX behaviour - ftruncate only works once on the initial creation of the segment. Any subsequent calls fail in this manner. The earliest reference I can find to this is a post to the apple mailing list.

If I put an shm_unlink before the shm_open the ftruncate works consistently.

assuming that you only want to resize the shared memory segment the once, you could wrap the ftruncate in an fstat to determine the current size and resize it in the case that st_size == 0

e.g.

struct stat mapstat;
if (-1 != fstat(fileHandle, &mapstat) && mapstat.st_size == 0) {
    ftruncate(fileHandle, 8192);
}


来源:https://stackoverflow.com/questions/25502229/ftruncate-not-working-on-posix-shared-memory-in-mac-os-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!