如果访问共享内存的关键是 shmget() 的返回值,那么拥有 key_t 的意义何在? [英] 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()?

查看:61
本文介绍了如果访问共享内存的关键是 shmget() 的返回值,那么拥有 key_t 的意义何在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用共享内存时,为什么要关心创建密钥

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

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

在下面的代码中?

key_t key;
int shmid;

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

据我所知,访问给定共享内存所需的是 shmid,而不是密钥.还是我错了?如果我们需要的是shmid,那么不只是每次都创建一个随机密钥有什么意义?

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?

@Beej 的 Unix IPC 指南阅读:

这个 key 废话怎么样?怎么办我们创造一个?那么,由于类型key_t 其实只是一个long,你可以使用任何你想要的号码.但是如果你对数字和一些进行硬编码其他不相关的程序硬编码相同的号码但想要另一个队列?解决方案是使用 ftok()生成密钥的函数两个参数.

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?

推荐答案

是的,您需要使用 shmid 打开共享内存后(使用 shmat())shmget().但是您将访问的特定共享内存块基于您使用的密钥,即希望通过 shm 进行通信的不同进程将需要使用相同的密钥.如果您只是使用随机数作为密钥,您可能会与其他一些不相关的程序发生冲突.

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.

我打算建议看看 Beej 的 IPC 指南 但我看你已经找到了 :)

I was going to suggest taking a look at Beej's Guide to IPC but I see you've already found it :)

这篇关于如果访问共享内存的关键是 shmget() 的返回值,那么拥有 key_t 的意义何在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆