ftruncate不工作的POSIX共享内存在Mac OS X [英] ftruncate not working on POSIX shared memory in Mac OS X
问题描述
我已经写在Mac OS X中的code使用POSIX共享内存,如下所示:
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
Linux上的工作没有任何问题。在Mac OS X,它返回-1和错误号
是 EINVAL
(如被看见在调试器)。
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?
推荐答案
这看起来像OSX行为 - ftruncate仅在段的初始的创建的工作一次。任何后续调用失败以这种方式。该最早提到我能找到这是一个后苹果的邮件列表。
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.
如果我把一个 shm_unlink
的的shm_open
的ftruncate都能正常工作了。
If I put an shm_unlink
before the shm_open
the ftruncate works consistently.
假设你只是想调整共享内存段的一次,你可以包装在ftruncate一个 FSTAT
来确定当前的大小和的情况下调整它的 st_size == 0
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
例如
struct stat mapstat;
if (-1 != fstat(fileHandle, &mapstat) && mapstat.st_size == 0) {
ftruncate(fileHandle, 8192);
}
这篇关于ftruncate不工作的POSIX共享内存在Mac OS X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!