When we do the Linux interprocess communication development, we often use the Ftok function to produce the unique key value of the text, then how this key value is generated.
Function prototype:key_t ftok (const char * fname, int id); Application:
key_t Key=ftok (".", ' A ');
FName is a file name that already exists, this article is "." Represents the current directory, the ID is a sub-ordinal, and the value range is only 8bits (0-255).
Here we give an example of how to generate the key value, the code ftok_test.c as follows:
- #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;
- }
Copy Code
The results of the operation are as follows:
$./a.out
The file Info:ftok (filename, ' A ') = 41015bb5, St_ino = c5bb5, St_dev = Ca01
The 16 process value of the capital letter ' a ' is 0x41.
You can see that the key value is a sub-ordinal value is the capital letter ' a ' 16 process value "41", plus st_dev two bits "01", plus st_info four bits "5BB5" composition "5bb5".
Note: The stat structure is as follows:
struct STAT {
unsigned long st_dev;//device number of the file
unsigned long St_ino;//Node
unsigned short st_mode;//file type and access permissions
unsigned short st_nlink;//The number of hard connections to the file, the newly created file value is 1
unsigned short st_uid;//user ID
unsigned short st_gid;//group 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;
};
How function Ftok in Linux generates key values