我正在尝试打开一个共享内存文件并写入其中。问题是 ftruncate 正在返回 -1。
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include<sys/mman.h>
#include<sys/stat.h>
#include <fcntl.h>
int main(void) {
int fd;
fd=shm_open("/shmem-m", O_CREAT,0777);
printf("%d\n",fd);
int a=ftruncate(fd, 1024);
printf("%d\n",a);
void* addr=mmap(NULL, 1024, PROT_READ|PROT_WRITE, MAP_SHARED,fd, 0);
char* msg= "hola mundo!";
memcpy(addr,msg,strlen(msg));
exit(EXIT_SUCCESS);
//return 0;
}
输出是:
3
-1
Segmentation fault
有什么想法吗?非常感谢
最佳答案
问题是 POSIX 要求以写入模式打开文件才能成功调用 ftruncate
,如 ftruncate man page 中所述.
因此对 shm_open
的调用变为 shm_open("/shmem-m", O_CREAT | O_RDWR, 0777)
,带有 O_RDWR
标志设置(shm_open man page)。
关于C Linux 共享内存错误 - ftruncate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25749186/