title: Assigning an array of posix semaphores to shared memory
body: <p>I would like to write an array of unnamed semaphores to shared memory so I can access them in forked processes. Here's what I have so far:</p>
  
  <pre><code>int main(int argc, char *argv[]){
  
  int num_process = atoi(argv[1]);
  int i = 0;
  
  int ppid = getpid();
  void *addr;
  
  int numsems = 512;
  int object_size = numsems * sizeof(sem_t);
  
  printf("declaring semaphores\n");
  sem_t *sem[numsems];
  
  //create shared memory and check that it worked
  printf("opening shared memory\n");
  int shmem_fd = shm_open("/my_shmem", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
  
  if(shmem_fd == -1){
      perror("Can't open shmem object");
      exit(-1);
  }
  
  //truncate memory object
  if(ftruncate(shmem_fd, object_size) == -1){
      perror("failed to resize shmem object");
      exit(-1);
  }
  
  addr = mmap(NULL, object_size, PROT_READ | PROT_WRITE, MAP_SHARED, shmem_fd, 0);
  
  if(MAP_FAILED == addr){
      perror("Map failed");
      exit(-1);
  }
  
  //store the semaphores at the start
  printf("initializing semaphores\n");
  
  for(i = 0; i&lt;numsems; i++){
      sem[i] = addr + i*sizeof(sem_t);
      if(sem_init(sem[i], 1, 0) == -1){
              perror("sem_init failed");
              exit(-1);
      }
  }
  
  //create children
  while((getpid() == ppid) &amp;&amp; (i &lt; num_process)){
  
  
      switch(fork()){
      case -1:
      printf("fork %d failed\n", i);
      break;
  
      case 0:
      //child process
      printf("child created\n");
      child_program( sem, numsems);
      printf("child done\n");
      break;
  
      default: //parent continues on to create next child
      break;
  
      }
  i++;
  }
  }
  </code></pre>
  
  <p>Which compiles fine but when I try to run it I get a segmentation fault when it gets to the <code>sem_t *sem[numsems]</code> part. I've read elsewhere that you shouldn't create a pointer to semaphores but when I didn't and tried <code>&amp;sem = addr</code> I got an error about needing a lvalue. Any help would be much appreciated.</p>