Creating shared memory in C

I created the following method in C to create a shared memory segment to hold the counter value. But I cannot store data in this segment. When I try to print the counter value it gives me the garbage value. Wrong with this code?

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);
    }
  }
}

      

This method is called inside the main method as follows.

   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;
    }

      

+3


source to share





All Articles