[英]Shared pointer to an array in shared memory, pointer doesn't seem shared?
我在共享內存中有一個數組。 我想使用一個指針迭代這個數組,這也是為了共享。 這是我嘗試過的:
/* 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];
現在我分叉子並嘗試更改值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指向時,從子進程打印時效果是可見的。 但是增量指針不起作用。
實際上你有兩個問題,但有一個是由操作系統緩解的。
第一個問題是你說你的共享內存大小為1( sizeof(char)
)。 這可以通過操作系統減輕,因為它可以將其四舍五入到頁面大小。
第二個問題是:
p = (char*) shmat(shmid, NULL, 0); /* pointer to queue in shared memory */
p = &queue[0];
在這里你從共享內存獲取p
,你用另一個指針覆蓋這個指針。
然而,出於兩個原因,這是一個沒有實際意義的問題:第一個是我評論過的問題。 第二個是即使你沒有覆蓋指針p
它仍然是你的進程的“本地”,所以做例如p++
不會改變共享內存中的副本,因為實際的指針不是共享的。 如果你真的想在共享內存中有一個指針,那么p
將是一個指向指針的指針,必須做(*p)++
來增加本地和共享內存中的指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.