Shared pointer to an array in shared memory, pointer doesn't seem shared?

I have an array in shared memory. I want to use a pointer for iterating through this array, which also is meant to be shared. Here is what I tried: /* initialize color sequence in shared memory */ shmkey = ftok("/dev/null",3); /* executable name and a random number */ shmid = shmget(shmkey, sizeof(char), 0700 | IPC_CREAT); if(shmid < 0){ /* shared memory error check */ perror("shmget\n"); exit(1); } queue = (char*) shmat(shmid, NULL, 0); /* shared memory part of colorSequence */ printf("queue allocated.\n"); /* initialize color sequence pointer in shared memory */ shmkey = ftok("/dev/null//",61); /* executable name and a random number */ shmid = shmget(shmkey, sizeof(char), 0700 | IPC_CREAT); if(shmid < 0){ /* shared memory error check */ perror("shmget\n"); exit(1); } p = (char*) shmat(shmid, NULL, 0); /* pointer to queue in shared memory */ printf("queue pointer allocated.\n"); p = &queue[0]; Now I fork the child and try to change the value p, but a change made in one process doesn't affect the other. if(fork() == 0){ /* child process */ sem_wait(&sem); printf(" Child printing *p=%c, p=%p\n",*p,p); p++; printf(" Child printing after++ p=%c, p=%p\n",*p,p); sem_post(&sem); exit(0); } else{ /* parent process */ sem_wait(&sem); printf("Parent printing *p=%c, p=%p\n",*p,p); p+=2; printf("Parnet printing after++ p=%c, p=%p\n",*p,p); p = NULL; //even though this, program doesn't fail sem_post(&sem); } Yet, the output is (Contents of queue is as follows: R B G . . .) : Parent printing *p=R, p=0x7f5c77837000 Parnet printing after++ p=B, p=0x7f5c77837002 Child printing *p=R, p=0x7f5c77837000 Child printing after++ p=G, p=0x7f5c77837001 I couldn't figure out why I get these results even though the pointer is supposed to be shared. Can you help me fix this? Thanks. **EDIT** When I try to change the value p points to in parent process, the effects are visible when printing from child process. However incrementing pointer doesn't work.
You can share memory, but you can't share a pointer. Remember that the (virtual) memory map is unique for each process. A pointer to shared memory in one process may (and most likely will) not be the same as a pointer to the same shared memory in another process.

以上就是Shared pointer to an array in shared memory, pointer doesn't seem shared?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » CSS3 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏