[英]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: 我在Mac OS X上编写了一个代码来使用POSIX共享内存,如下所示:
#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. Linux上的ftruncate
工作没有任何问题。 On Mac OS X, it is returning -1 and errno
is EINVAL
(as seen in the debugger). 在Mac OS X上,它返回-1,而errno
是EINVAL
(如调试器中所示)。
Why is it failing? 它为什么失败? What is being missed here? 这里错过了什么?
This looks like OSX behaviour - ftruncate only works once on the initial creation of the segment. 这看起来像OSX行为 - ftruncate仅在初始创建段时才有效。 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. 如果我在shm_open
之前放置一个shm_unlink
,那么ftruncate会一直工作。
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
假设您只想重新调整共享内存段的大小,您可以将ftruncate包装在fstat
以确定当前大小并在st_size == 0
的情况下调整大小
eg 例如
struct stat mapstat;
if (-1 != fstat(fileHandle, &mapstat) && mapstat.st_size == 0) {
ftruncate(fileHandle, 8192);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.