Function prototypes
key_t Ftok (const char *pathname, int proj_id); #pathname: Specifies the file name, the file must be present and can be accessed #proj_id: sub-sequence number, only 8 bits are used (0-255) #当成功执行时, Returns a key_t value that fails to return-1
Ftok Implementation principle
The key_t returned by Ftok is a 32-bit value in Linux by taking the minimum of 8 significant bits of the PROJ_ID parameter, A minimum of 8 significant digits that contain the minor device number of the device for the file system to which the specified file belongs, and the minimum 16 significant digits of the I-node number of the file specified by pathname. Pathname.
Example:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include < sys/stat.h> #include <sys/ipc.h> #define Proj_mask 0x000000ff#define inode_mask 0x0000ffff#define minor_mask 0x000000ffkey_t Ipc_ftok (const char *pathname, int proj_id) { struct stat buf; Long minor_id = 0L, inode_id = 0L; key_t key = 0; if (stat (pathname, &buf) = =-1 | |!proj_id) { return-1; } minor_id = (long) minor (Buf.st_dev); inode_id = (long) Buf.st_ino; Key = inode_id & Inode_mask; Key |= (minor_id & Minor_mask) <<, key |= (proj_id & Proj_mask) <<; Return key;} int main (int argc, char *argv[]) { if (argc! = 3) { printf ("%s pathname proj_id\n", argv[0]); return 1; } printf ("Ipc_ftok = 0x%x, Ftok = 0x%x\n", Ipc_ftok (Argv[1], atoi (argv[2])), Ftok (Argv[1], atoi (argv[2))); return 0;}
In practice, it is easy to understand that, in the same situation as PROJ_ID, you can ensure that the Ftok returns always-consistent key values as long as the file (or directory) name is not changed. However, this understanding is not entirely correct, and it is possible to bury a very subtle trap in application development. Because the implementation of Ftok has the risk that in the time period when multiple processes accessing the same shared memory call the Ftok function successively, if the file (or directory) pathname specified is deleted and recreated, the file system assigns the new I-node information to the file (or directory) with the same name. As a result, the ftok called by these processes can return normally, but the resulting key values are not guaranteed to be the same. The possible consequence is that these processes originally intended to access an identical shared memory object, but because of their respective key values, the shared memory that the process points to is no longer consistent, and if the shared memory is created, no errors will be reported on the surface during the entire application run. However, the purpose of data transfer through a shared memory object cannot be achieved.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Linux Ftok () function