我在 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;
}
在Linux上,ftruncate
正常工作。在Mac OS X上,它返回-1,并且errno
是EINVAL
(通过调试器查看)。
为什么会失败?这里漏掉了什么?
EINVAL
。那么,p_size
的值是多少?如果您打开并截断常规文件,然后使用mmap
,是否会发生同样的情况? - Useless