doptimusprime
doptimusprime

Reputation: 9411

ftruncate not working on POSIX shared memory in Mac OS X

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?

Upvotes: 12

Views: 3571

Answers (1)

Anya Shenanigans
Anya Shenanigans

Reputation: 94829

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);
}

Upvotes: 14

Related Questions