目前我的共享内存在两个进程之间工作 我的 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/