Shared memory: what’s the difference between the key and the id?

Shared memory: what’s the difference between the key and the id?

When invoking ipcs -a, what is the difference between the key column and the id column?

Here is an example output for ipcs command:

ipcs -a

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0x00000000 0          ybaumes    600        393216     2          dest         
0x00000000 65537      ybaumes    700        8124648    2          dest         
0x00000000 3932163    ybaumes    700        169376     2          dest         
0x00000000 3604485    ybaumes    600        393216     2          dest         

Firstly, the ‘id’ column in shared memory refers to the specific handler to the shared memory area. If the shared memory area is not obtained, it will return a negative value. So basically, ‘id’ is generated by system and user doesn’t have any control over it.

While ‘key’ column in the ipcs command refers to the value which is given in reference to inter process communication resources like shared memory, message queues and semaphores. ‘A key is simply an integer of type key_t’. Moreover, the key argument is a access value associated with the semaphore ID. It can be simple integer number, eg. 34562, which can be passed at the time of creation of those resources using associated get functions.
the place where a key is required accepts a special parameter, IPC_PRIVATE. In this case, the system will generate a unique key and guarantee that no other process will have the same key.

If a resource is requested with IPC_PRIVATE in a place where a key is required, that process will receive a unique key for that resource. Since that resource is identified with a unique key unknown to the outsiders, other processes will not be able to share that resource and, as a result, the requesting process is guaranteed that it owns and accesses that resource exclusively.

This concept get more clear when it is used in terms of message queues, where a message is generated and sent with a specific key value. The same message can only be received at the receiving end when, the given key is matched at the receiver end. Because, there also return value gives the message id, which is calculated on the corresponding key value, main relevance is for checking for uniqueness of a resource.