What is the point of having a key_t if what will be the key to access shared memory is the return value of shmget()?

devoured elysium picture devoured elysium · Nov 14, 2010 · Viewed 21.4k times · Source

When using shared memory, why should we care about creating a key

key_t ftok(const char *path, int id);

in the following bit of code?

key_t key;
int shmid;

key = ftok("/home/beej/somefile3", 'R');
shmid = shmget(key, 1024, 0644 | IPC_CREAT);

From what I've come to understand, what is needed to access a given shared memory is the shmid, not the key. Or am I wrong? If what we need is the shmid, what is the point in not just creating a random key every time?

Edit

@Beej's Guide to Unix IPC one can read:

What about this key nonsense? How do we create one? Well, since the type key_t is actually just a long, you can use any number you want. But what if you hard-code the number and some other unrelated program hardcodes the same number but wants another queue? The solution is to use the ftok() function which generates a key from two arguments.

Reading this, it gives me the impression that what one needs to attach to a shared-memory block is the key. But this isn't true, is it?

Answer

R.. GitHub STOP HELPING ICE picture R.. GitHub STOP HELPING ICE · Nov 14, 2010

The whole System V IPC system is full of bad designs like this. (By bad designs, I mean a tiny namespace for shared resources where you have to rely on stupid tricks like ftok to get a key and pray it doesn't happen to conflict with any other keys in use.)

If possible, I would pretend it doesn't exist and use POSIX shared memory instead whenever possible (and likewise POSIX thread synchronization primitives in place of System V semaphores). The only instance I can think of where you need System V shared memory is for the X shared-memory image extension and perhaps other X extensions.

Edit: To better answer OP's question about the purpose of ftok: key_t is usually 32-bit and yes you could just pick a 32-bit number yourself, but the problem is that humans are not equally likely to pick all numbers, and the chance of collision is way too high. ftok lets you choose a file (intended to be one unique to your application) and an integer and hash the file's inode number with your chosen integer, which should result in much more even distribution of key choices across the key space. Of course you could also just choose a key with rand as long as you have a way of passing the result to other processes that need to attach the shared memory.