一 点睛
key_t ftok( char * fname, int id )
- fname:就是指定的文件(存在,可以访问的)名。
- id:子序号。
ftok函数是根据fname和id来创建一个关键字(类型为 key_t),此关键字在创建信号量,创建消息队列的时候都需要使用。
其中fname必须是一个存在的可访问的路径或文件,id必须不得为0。
失败返回值为-1。
二 生成一个键值
1 代码
#include <stdio.h>
#include <sys/sem.h>
#include <stdlib.h>
int main()
{
key_t semkey;
if((semkey = ftok("./test", 123))<0)
{
printf("ftok failed\n");
exit(EXIT_FAILURE);
}
printf("ftok ok ,semkey = %d\n", semkey);
return 0;
}
2 运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
ftok ok ,semkey = 2063613028
3 说明
用当前路径下的test程序文件和123一起生成一个键值,最后打印出来。
二 解开ftok产生健值的内幕
1 代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/sem.h>
int main()
{
char filename[50];
struct stat buf;
int ret;
strcpy( filename, "./test" );
ret = stat( filename, &buf );
if( ret )
{
printf( "stat error\n" );
return -1;
}
printf( "the file info: ftok( filename, 0x27 ) = %x, st_ino = %x, st_dev= %x\n", ftok( filename, 0x27 ), buf.st_ino, buf.st_dev );
return 0;
}
2 运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
the file info: ftok( filename, 0x27 ) = 2700012d, st_ino = 1012d, st_dev= fd00
3 说明
ftok获取的健值是由ftok函数的第二个参数的后8位,st_dev的后8位,st_ino的后16位构成的。