加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

有一个key_t的意义是什么是访问共享内存的关键是shmget()的返回

发布时间:2020-12-16 05:29:05 所属栏目:百科 来源:网络整理
导读:当使用共享内存时,为什么要关心创建一个密钥 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); 从我所了解的,访问给定的共享内存所需要的
当使用共享内存时,为什么要关心创建一个密钥
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,那么每次不只是创建一个随机密钥的要点是什么?

编辑

@ Beej’s Guide to Unix IPC可以看:

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.

阅读这个,这给我的印象是,需要附加到共享内存块是一个关键.但这不是真的吗?

解决方法

是的,在使用shmget()打开它之后,您需要使用shmid访问共享内存(使用shmat()).但是,您要访问的共享内存的具体块基于您正在使用的密钥,即,希望通过shm进行通信的不同进程将需要使用相同的密钥.如果你只是使用一个随机数作为关键,你可能会遇到一些其他无关的程序.

我打算建议看看Beej’s Guide to IPC,但我看到你已经找到了:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读