title: How does Linux Kernel assigns memory pointers when a process uses shm_open()?
body: <p>I'm on Linux 2.6 and I have a weird problem. I have 3 concurrent processes (forked from the same process) which need to obtain 3 DIFFERENT shared memory segments, one for each process. Each of the process executes this code (please note that 'message' type is user-defined)</p>
  
  <pre><code>    message *m;
      int fd = shm_open("message", O_CREAT|O_RDWR, S_IRUSR|S_IWUSR);
      ftruncate(fd, sizeof(message));
      m = mmap(NULL, sizeof(message), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
      char messagename[16];
      snprintf(messagename, sizeof(messagename), "%p", m);
      char path[32] = "/dev/shm/";
      strcat(path, messagename);
      rename("/dev/shm/message", path);
  </code></pre>
  
  <p>Let me explain a bit: I want every process to allocate a shared memory zone which contains a message. To make sure another process (the message receiver) can access the same shm, I then rename my shm file from "message" to a string named after the message pointer (this because the process which receives the message already knows the pointer).</p>
  
  <p>When executing the program, though, I tried to print (for debugging purpose) the pointers that every process received when mmapping the fd obtained with shm_open, and I noticed that all of them got the SAME pointer. How is it possible? I thought that maybe other processes did the shm_open() after the first one did and before it renamed the segment, so I also tried to make these lines of code an atomic operation by using a process shared mutex, but the problem persists.</p>
  
  <p>I would really appreciate any kind of help or suggestion.</p>