Ftruncate does not work in POSIX shared memory on Mac OS X

I wrote 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 works without problems. On Mac OS X, it returns -1, and errno returns EINVAL (as shown in the debugger).

Why does he fail? What is missing here?

+7
c linux shared-memory macos
source share
1 answer

This is similar to OSX behavior. ftruncate only works once during the initial creation of a segment. Any subsequent calls fail in this way. earliest link I can find this message on the apple mailing list.

If I put shm_unlink before shm_open , ftruncate works sequentially.

Assuming that you want to change the size of the shared memory segment only once, you can wrap ftruncate in fstat to determine the current size and change its size in case st_size == 0

eg.

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

All Articles