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()?

无人久伴 提交于 2019-12-03 05:41:30
Toby

Yes, you need to use the shmid to access the shared memory (using shmat()) after you've opened it using shmget(). 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 :)

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.

shmid values are only valid in the context of a single process, whereas the same key_t value in different processes will allow them to open the same shared memory segment.

That's essentially why you need a key_t - as a cross-process way of naming a shared memory segment. As for ftok(), as the other answers have noted, that's used to reduce the probability of two unrelated groups of processes using the same key_t value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!