我正在使用共享内存段并遇到了这个奇怪的问题。
我正在尝试在许多进程之间共享一个结构:
struct shmstruct{
int pid[50];
char user[50][10];
};
struct shmstruct *shmobj;
void *shmp;
int main()
{
//server creates shared memory
if((shmid = shmget((key_t)1234,sizeof(struct shmstruct),0666|IPC_CREAT)) == -1){
fprintf(stderr,"shmget failed\n");
exit(EXIT_FAILURE);
}
//server attaches shared memory segment to pointer (void *)
if((shmp = shmat(shmid,(void *) 0,0)) == (void *)-1){
fprintf(stderr,"shmat failed\n");
exit(EXIT_FAILURE);
}
//structure is now linked with shared memory pointer
printf("Memory attached at %X\n",shmp);
shmobj = (struct shmstruct *)shmp;
int i;
for(i = 0; i < 50; i++)
if(shmobj->pid[i]!=0)
printf("shminit:i:%d user:%s pid:%d\n", i, shmobj->user[i], shmobj->pid[i]);
}
但是每当我创建和附加共享内存段时,shmobj->pid[1] 已经被初始化为 2673!
printf 的结果总是:
shminit:i:1 user: pid:2673
关于为什么会发生这种情况的任何想法?
先感谢您!