title: Busy waiting and shared memory
body: <p>I am currently trying to implement a single C program that creates a shared memory area for a given process then forks this process into one child, makes the child to write into a given position of the shared memory and has the father wait for until the child writes in that position. I used a simple busy waiting approach, suffering the parent process to wait until the child end his writing using a while loop. The problem is that it only works when I introduce some delay in that loop. Anyone has any idea why is this so?</p>
  
  <p>Code:</p>
  
  <pre><code>int shmid;
  int *shmptr;
  int i, j, ret;
  
  key_t key = SHM_KEY;
  
  // Create shared memory segment
  if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0600)) &lt; 0)
  {
      printf("shmget error: %s\n", strerror(errno));
      return -1;
  }
  
  // Attach shared memory segment
  if ((shmptr = shmat(shmid, 0, 0)) == (void *) -1)
  {
      puts("shmat error");
      return -1;
  }   
  
  shmptr[6] = '%';
  
  ret = fork();
  if (ret &gt; 0) 
  {/*parent*/
      /*here is the loop that implements the busy waiting approach*/
      while (shmptr[6] != '^') {
          sleep(1);
      }
      for (i = 0; i &lt; 7; i++) printf("%c", shmptr[i]);
      puts("");
  
      int status = 0;
      wait(&amp;status);
  }
  else 
  {/*child*/
      shmptr[0] = 's';
      shmptr[1] = 'h';
      shmptr[2] = 'a';
      shmptr[3] = 'r';
      shmptr[4] = 'e';
      shmptr[5] = 'd';
  
      /*tell parent process ithas finished its writing*/
      shmptr[6] = '^';
  
      exit(0);
  }
  </code></pre>