C Linux共享内存错误 - ftruncate

时间:2014-09-09 15:59:16

标签: c memory shared

我试图打开共享内存文件并写入其中。问题是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

有什么想法吗?非常感谢你

1 个答案:

答案 0 :(得分:2)

问题是POSIX要求在写入模式下打开文件,以便ftruncate的调用成功,如ftruncate man page中所述。

因此,对shm_open的调用变为shm_open("/shmem-m", O_CREAT | O_RDWR, 0777),并设置了O_RDWR标记(shm_open man page)。

相关问题