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 typekey_t
is actually just along
, 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 theftok()
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?
Yes, you need to use the shmid to access the shared memory (using
shmat()
) after you've opened it usingshmget()
. But the specific block of shared memory that you'll be accessing is based on the key that you are using i.e. different process wishing to communicate via the shm will need to use the same key. If you just used a random number as a key, you might get a clash with some other unrelated program.I was going to suggest taking a look at Beej's Guide to IPC but I see you've already found it :)