我们在做linux 进程间通信开发时,经常会用到ftok函数去产文唯一键值,那么这个键值是如何产生的呢。
函数原型:key_t ftok( const char * fname, int id );应用:
key_t key=ftok(".",‘A‘);
fname为已经存在的文件名,本文为“.”表示当前目录; id为子序号,值范围只有8bits(0-255)。
下面我们举例说明如何产生键值,代码ftok_test.c如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/stat.h>
- int main()
- {
- char filename[50];
- struct stat buf;
- int ret;
- strcpy( filename, "." );
- ret = stat( filename, &buf );
- if( ret )
- {
- printf( "stat error\n" );
- return -1;
- }
- printf( "the file info: ftok( filename, ‘A‘ ) = %x, st_ino = %x, st_dev = %x\n", ftok( filename, ‘A‘), buf.st_ino, buf.st_dev );
- return 0;
- }
复制代码
运行结果如下:
$ ./a.out
the file info: ftok( filename, ‘A‘ ) = 41015bb5, st_ino = c5bb5, st_dev = ca01
大写字母‘A’的十六进程值为0x41.
可以看出键值是由子序号值也就是大写字母‘A‘的十六进程值”41“,加上st_dev的后两位”01“,再加上st_info的后四位”5bb5“组成“41 01 5bb5”。
注:stat结构如下:
struct stat {
unsigned long st_dev; //文件的设备编号
unsigned long st_ino; //节点
unsigned short st_mode; //文件的类型和存取的权限
unsigned short st_nlink; //连到该文件的硬连接数目,刚建立的文件值为1
unsigned short st_uid; //用户ID
unsigned short st_gid; //组ID
unsigned long st_rdev;
unsigned long st_size;
unsigned long st_blksize;
unsigned long st_blocks;
unsigned long st_atime;
unsigned long st_atime_nsec;
unsigned long st_mtime;
unsigned long st_mtime_nsec;
unsigned long st_ctime;
unsigned long st_ctime_nsec;
unsigned long __unused4;
unsigned long __unused5;
};
原文地址:https://www.cnblogs.com/wudymand/p/9226470.html