views:

162

answers:

2

The function which creates shared memory in *inux programming takes a key as one of its parameters..

What is the meaning of this key? And How can I use it?

Edit:

Not shared memory id

+3  A: 

It's just a System V IPC (inter-process communications) key so different processes can create or attach to the same block of shared memory. The key is typically created with ftok() which turns a fully-specified filename and project ID into a usable key.

Since an application can generally use the same filename in all its different processes (the filename is often a configuration file associated with your application), each different process gets the same key (or, more likely if your using the project ID to specify multiple shared memory segments, the same set of keys).

For example, we once had an application that used a configuration file processed by our lex/yacc code so we just used that pathname and one project ID for each different shared memory block (there were three or four depending on the purpose of the process in question). This actually made a lot of sense since it was the parsed and evaluated data from that configuration file that was stored in the shared memory blocks.

Since no other application on the system should be using our configuration file for making a key, there was no conflict. The key itself is not limited to shared memory, it could be used for semaphores and other IPC mechanisms as well.

paxdiablo
Yes, the key is in general created with `ftok` (see http://netbsd.gw.com/cgi-bin/man-cgi?ftok+3+NetBSD-current), and used from `shmget`.Using the key, `shmget` can either create the shared segment, or obtain the existing segment identified with the key, depending on the flags you pass (see http://netbsd.gw.com/cgi-bin/man-cgi?shmget+2+NetBSD-current).
tonio
A: 

The posix shared memory functions (shm_open and friends) have a more user-friendly interface in that they can accept a unique filename which must be used by the applications to open the same shared memory block.

Having said that, it is generally also feasible to open a file in /dev/shm under Linux and then mmap it with MAP_SHARED which achieves much the same.

MarkR