ftok到底有什么好处?

sabirer 2009-07-09 02:01:45
我看到很多操作IPC,例如消息队列,共享内存等的时候,常常的key并不是直接写死的,而是用ftok返回的键值作为IPC键值,请问这样做有什么好处吗?直接写死,或者写到配置文件中不是也一样吗?

我自己写了几行测试代码,发现一样也都可以做大,请问为什么还是都用 ftok呢?请不吝赐教。
...全文
789 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
kerven1988 2010-03-30
  • 打赏
  • 举报
回复
领教,谢谢
john 2010-03-02
  • 打赏
  • 举报
回复
使用ftok是为了防止冲突。 避免不慎使用到了正在使用的key上去。
billow_zhang 2009-07-10
  • 打赏
  • 举报
回复

ftok的第一个参数是一个文件的路径名称.一般在应用系统中,使用$HOME或者应用系统的根目录作为它的值.这样产生的key_t就不会与系统中其他的软件和系统的相同了,从而避免造成冲突.

如果,你使用配制文件,或者写死在程序里面,key_t的值有可能与系统中其他的软件.
ftok的第二个参数是用于你在自己的系统里产生多个IPC的时候,区分它们使用的.

总之, ftok的首个参数是用于与其他系统相区别的.
第二个参数是用于本系统的不同的IPC区别使用的.

mymtom 2009-07-10
  • 打赏
  • 举报
回复
[Quote=引用楼主 sabirer 的帖子:]
我看到很多操作IPC,例如消息队列,共享内存等的时候,常常的key并不是直接写死的,而是用ftok返回的键值作为IPC键值,请问这样做有什么好处吗?直接写死,或者写到配置文件中不是也一样吗?

我自己写了几行测试代码,发现一样也都可以做大,请问为什么还是都用 ftok呢?请不吝赐教。
[/Quote]
ftok没有什么好处,可是不用的话,可能会又很大的坏处。
  • 打赏
  • 举报
回复
ftok - generate an IPC key

SYNOPSIS

#include <sys/ipc.h>

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


DESCRIPTION

The ftok() function returns a key based on path and id that is usable in subsequent calls to msgget(), semget() and shmget(). The path argument must be the pathname of an existing file that the process is able to stat().
The ftok() function will return the same key value for all paths that name the same file, when called with the same id value, and will return different key values when called with different id values or with paths that name different files existing on the same file system at the same time. It is unspecified whether ftok() returns the same key value when called again after the file named by path is removed and recreated with the same name.

Only the low order 8-bits of id are significant. The behaviour of ftok() is unspecified if these bits are 0.
sabirer 2009-07-09
  • 打赏
  • 举报
回复
那么不用 ftok来分配key给IPC,自己写死可以吗?这样会不会有什么问题?
ShowMan 2009-07-09
  • 打赏
  • 举报
回复
ftok应用范围:在IPC通信及消息记者中使用

解析:

系统建立IPC通讯(如消息队列、共享内存时)必须指定一个ID值。通常情况下,该id值通过ftok函数得到。

在一般的UNIX实现中,是将文件的索引节点号取出,前面加上子序号得到key_t的返回值。

如指定文件的索引节点号为65538,换算成16进制为0x010002,而你指定的ID值为38,换算成16进制为0x26,则最后的key_t返回值为0x26010002。
hefuhua 2009-07-09
  • 打赏
  • 举报
回复
http://www.9php.com/FAQ/cxsjl/c/2007/02/627382674652.html

http://topic.csdn.net/u/20081205/15/4b50e50a-a396-403b-a60a-95a86322eac2.html

上面这两个资料看看对你有没有帮助
sabirer 2009-07-09
  • 打赏
  • 举报
回复
自己顶

23,116

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧