views:

236

answers:

2

Could someone provide an example of (reasonably) using the function shmat() with non-null second parameter?

The manual says:

#include <sys/shm.h>

void *shmat(int shmid, const void *shmaddr, int shmflg);

The shmat() function attaches the shared memory segment associated with the shared memory identifier shmid to the data segment of the calling process. The segment is attached at the address specified by one of the following criteria:

  • If shmaddr is a NULL pointer, the segment is attached at the first available address as selected by the system.
  • If shmaddr is not a NULL pointer and (shmflg & SHM_RND) is non-zero, the segment is attached at the address given by (shmaddr - (shmaddr % SHMLBA)).
  • If shmaddr is not a NULL pointer and (shmflg & SHM_RND) is 0, the segment is attached at the address given by shmaddr.

but I have never seen any example of shmat used with anything but shmaddr set to NULL. In my project, a process got to attach it to a malloc()'ed piece of memory just okay, and could use it just fine, then another process acquired the pointer to that shared memory (by shmid), then segfaulted while trying to access the memory.

A: 

I imagine it's so that you can share a structure with absolute pointers in it.

But I don't have any code samples.

Douglas Leeder
+1  A: 

The idea here is to have shared segment placed at the same virtual address in different processes so they can use plain pointers (and not offsets) to address items in shared memory. The common scenario is for single "master" process to map memory at kernel-provided address (second argument zero,) then communicate that address to "worker" processes via some out-of-band channel (like a command argument with fork/exec, UNIX socket, FIFO, etc.), then the "workers" try mapping the segment at that address. Again, the idea is that if the kernel was able to map shared memory at given VA for the "master", the same address should be fine for "worker" processes.

I don't have a "reasonable" example to point to. You can take a look at how Postgres works with shared memory. It's a bit involved though.

Nikolai N Fetissov
...but if the "workers" use the same key for shmget, they don't need the address - shmat will return a pointer to the same chunk of (already created) shared memory with shmaddr=NULL just the same. Where's the difference?
SF.
The difference is that shared memory is mapped at the same exact virtual address in all communicating processes, so one process can store pointers there (limited to the shared segment of course) and the others can use them directly.
Nikolai N Fetissov