在C中创build共享内存

我在C中创build了下面的方法来创build共享内存段来存储计数器值。 但是我不能在这个段中存储数据。当我尝试打印计数器的值时,它给了我一个垃圾值。这个代码有什么问题?

CreateCounter() { key = ftok(".",'B'); shmCntid = shmget(key,COUNTER_SIZE,IPC_CREAT|0666); if(shmCntid == -1 ) { perror("shmget"); exit(1); } else { printf("Creating new Sahred memory sement\n"); cntPtr = shmat(shmCntid,0,0); if(cntPtr == -1 ) { perror("shmat"); exit(1); } } } 

这个方法在main方法里面调用如下。

  int *cntPtr; int rowCnt; sem_t s; sem_t c; sem_t r; int main(int argc, int *argv[]) { int pid, pid2, pid3, i; CreateBuf1(); CreateBuf2(); CreateCounter(); GetInput(argv[1],*buf1Ptr); sem_init(&c, 0, 1); sem_init(&r, 0, 1); sem_init(&s, 0, 1); for( i = 0 ; i < 9; i++) { pid = fork(); if(pid < 0) { printf("Fork error !\n"); } else if (pid == 0) break; } if(pid < 0) { printf("Fork error !\n"); } else if (pid == 0) { sem_wait(&r); Grp1 (i,i); cntPtr+=rowCnt; sleep(1); sem_post(&r); sem_post(&c); exit(0); } else { wait(NULL); } pid2 = fork(); if(pid2 < 0) { printf("Fork error !\n"); } else if (pid2 == 0) { sem_wait(&c); Grp2(9); cntPtr+=colCnt; sleep(1); sem_post(&c); exit(0); } else { wait(NULL); } // This space is to print the values.............. shmctl(shmBuf1id,IPC_RMID,0); shmctl(shmBuf2id,IPC_RMID,0); shmctl(shmCntid,IPC_RMID,0); return 0; }