C - 使用 mmap 通过共享内存读取整数

标签 c shared-memory mmap

目前我的共享内存在两个进程之间工作 我的 parent 长这样

/* strings written to shared memory */
const char *message_0 = "Hello";
const char *message_1 = "World!";
/* shared memory file descriptor */
int shm_fd;
/* pointer to shared memory obect */
void *ptr;
/* create the shared memory object */
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
/* configure the size of the shared memory object */
ftruncate(shm_fd, SIZE);
/* memory map the shared memory object */
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
/* write to the shared memory object */
sprintf(ptr,"%s",message 0);
ptr += strlen(message_0);
sprintf(ptr,"%s",message 1);
ptr += strlen(message_1);

我的子进程接收到这样的代码

const char *name = "OS";
/* shared memory file descriptor */
int shm_fd;
/* pointer to shared memory obect */
void *ptr;
    /* open the shared memory object */
    shm_fd = shm_open(name,O_CREAT | O_RDWR, 0666);
    /* memory map the shared memory object */
    ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
    /* read from the shared memory object */
    //char message = ptr;
    //int newmsg;
    //newmsg = atoi(message);
    printf("%s",(char *)ptr);
    printf("\n");

现在我不想传递 hello world,而是想传递数组,所以我尝试更改父级的末尾以尝试传递单个整数。

sprintf(ptr, "%d", 5);
ptr += 20; //just used 20 since it should be big enough for now

在我的子进程中我改变了

printf("%d",(char *)ptr);

printf("%s", (int *)ptr);

但是我的消息总是在某处出错,我打印了一个无效的数字。谁能告诉我我错过了什么?

最佳答案

在通过内存传递数值时,您不应尝试将数值表示为字符串。您的接收者应该只是将指针指向您放置 int 的地址,并将其解释为 int:

child :

ptr = (int*) mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
....
int value = *ptr;

关于C - 使用 mmap 通过共享内存读取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29172104/

相关文章:

c - malloc 程序出错

c - gdb - 打印宏名称而不是值

c++ - 导入库如何工作以及为什么 MinGW 不需要它们?

c - setjmp 并省略帧指针

windows - Windows 上共享内存的映射 View 数

c - 不同类型的单个 mmap 指针

linux - 在 mmap 相同文件后删除 tmpfs(/dev/shm) 中的文件

c++ - 如何在 C++14 中将多字节值写入共享内存?

c - 使用共享内存将数据结构传递给另一个进程并保存到文件

python - 从 C++ 读取 npy 文件