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

时间:2015-03-20 17:07:41

标签: c shared-memory mmap

目前,我的共享内存在两个进程之间工作 我的父母看起来像这样

/* 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世界而是传递数组,所以我尝试更改父节点的末尾以尝试传递一个整数。

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);

然而,我的消息总是在某处混乱,而我打印的数字无效。谁能告诉我我错过了什么?

1 个答案:

答案 0 :(得分:1)

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

孩子:

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