我在共享内存中有一个数组。我想使用一个指针来遍历这个数组,这也是共享的。这是我尝试过的:
/* 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];
现在我 fork 孩子并尝试更改值 p,但是在一个进程中所做的更改不会影响另一个进程。
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);
}
然而,输出是(队列的内容如下:RBG ...):
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
即使应该共享指针,我也无法弄清楚为什么会得到这些结果。你能帮我解决这个问题吗?谢谢。
编辑
当我尝试在父进程中更改 p 指向的值时,从子进程打印时效果是可见的。但是递增指针不起作用。