[英]C - Reading an integer through shared memory with 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 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:
儿童:
ptr = (int*) mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
....
int value = *ptr;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.