0

i should write an program that write integers into a shared memory, fork a childprocess and the childprocess should read the integers.

shm.c

#define N_SHARED 2000

int main(int argc, char **argv) {
/* Ein Shared-Memory-Segment einrichten */
shmid = shmget(IPC_PRIVATE, N_SHARED, IPC_CREAT | SHM_R | SHM_W);

if (shmid == -1) {
 perror("shmid");
 exit(1);
}

 /* Pointer zu Sharedm-Memory-Segment erhalten */
shmData = (int *)shmat(shmid,0, N_SHARED);
if (shmData == (int *)(-1)) {
  perror("shmat");
  exit(1);
}

/** ininitalisieren des Zufallsgenerator durch aktuellen Zeitstempel */
srand48(time(NULL));
for (i=0; i<N_SHARED; i++) {
 shmData[i] = lrand48();
 printf("SHM-->%d-->%d\n",i+1,shmData[i]);
}

  pid = fork();

  snprintf(shmidArg,32, "%d", shmid);

  // Kindprozess
  if (pid == 0) {
    execlp("./shm_child",shmidArg,NULL);
  } else if (pid < 0) {
        perror("Kindprozess konnte nicht erzeugt werden!");
        return 1;
  }

shm_child.c

  #define N_SHARED 2000

  int i;
  int *shmData;
  static int shmid;

  int main(int argc, char **argv) {
    shmid = atoi(argv[0]);
    printf("shm_child shared memoryid:%d\n",shmid);

    /* Shared-Memory laden */
    shmData = (int *)shmat(shmid,0,0);
    if (shmData == (int *)(-1)) {
        perror("shmat");
        exit(1);
    }


    for(i=0;i<N_SHARED;i++) {
      printf("%d --> %d\n",i+1,shmData[i]);
    }

My problem: Every number after the index 1024 is 0 in the child_process but not in the main process.

Thank you

Ezak
  • 137
  • 1
  • 3
  • 14
  • 2
    I think that you didn't specify the correct size of the shared memory you created with the function shmget in the parent process. The second argument of this function should be `N_SHARED*sizeof(int)`. `shmid = shmget(IPC_PRIVATE, N_SHARED*sizeof(int), IPC_CREAT | SHM_R | SHM_W);` – shamba Jun 16 '17 at 20:58
  • The third argument to `shmat()` is a flag bitmask, but instead you seem to be passing the size (which is an inherent characteristic of the shared-memory segment). This is wrong, though it's unclear whether it explains your problem. – John Bollinger Jun 16 '17 at 21:01
  • @shamba That was the problem. Thank you very much ! – Ezak Jun 16 '17 at 21:02
  • @JohnBollinger yes thats true, it was only a try and should be 0. But that wasn't the problem ;) – Ezak Jun 16 '17 at 21:05

1 Answers1

2

I believe if you change #define N_SHARED 2000 to #define N_SHARED 2000*sizeof(int), you code should work as expected.

shmat allocates shared memory with size equal to the value of size rounded up to a multiple of PAGE_SIZE. You code tries to allocate 2000 bytes which is rounded to 4096, i.e. 1024 * sizeof(int). This explains why the first 1024 int has expected value.

wyc
  • 351
  • 2
  • 11