title: Shared Memory With Two Processes In C?
body: <p>I want to do the following:</p>
  
  <p>Parent process creates a child process. Then the child process reads n int's from the user and store them in a shared memory. The parent process then displays them.</p>
  
  <p>I reached the following:</p>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;sys/ipc.h&gt;
  #include &lt;sys/shm.h&gt;
  #include &lt;stdio.h&gt;
  #define SHMSIZE 27
  int main() {
     int shmid;
     int *shm;
     int *n;
  
     if(fork() == 0) {
        shmid = shmget(2009, SHMSIZE, 0);
        shm = shmat(shmid, 0, 0);
        n = shm;
        int i;
        for(i=0; i&lt;5; i++) {
           printf("Enter number&lt;%i&gt;: ", i);
           scanf("%d", n++);
        }
        printf ("Child wrote &lt;%d&gt;\n",shm);
        shmdt(shm);
     }
     else {
        wait();
        int *s;
        shmid = shmget(2009, SHMSIZE, 0666 | IPC_CREAT);
        shm = shmat(shmid, 0, 0);
        s = shm;
        wait(NULL);
        printf ("Parent reads &lt;%d&gt;\n",shm) ;
        shmdt(shm);
        shmctl(shmid, IPC_RMID, NULL);
     }
     return 0;
  }
  </code></pre>
  
  <p>And the output is just this line:</p>
  
  <pre><code>Enter number&lt;1&gt;:
  </code></pre>
  
  <p>And if I entered a number, let's say 25, it outputs this:</p>
  
  <pre><code>Parent reads &lt;r&gt;
  </code></pre>
  
  <p><em>r: random -ve number changes every time I execute the code</em></p>
  
  <p>It never went through the child process code ! Am I doing this in a wrong way ?</p>