An ID value must be specified for the system to establish IPC communication (such as message queue and shared memory. Generally, this ID value is obtained through the ftok function.
The ftok prototype is as follows:
Key_t ftok (char * fname, int ID)
Fname indicates the name of the file you specified (the file must exist and be accessible), and Id indicates the sub-serial number, Although it is an int, only 8 bits are used (0-255 ).
When the execution is successful, a key_t value will be returned, otherwise-1 will be returned.
In the general UNIX implementation, the index node number of the file is taken out, and the return value of key_t is obtained by adding the sub-number before it. For example, if the index node number of a specified file is 65538, it is converted into a hexadecimal value of 0x010002, And the id value you specified is 38, it is converted into a hexadecimal value of 0x26, then the final key_t return value is 0x26010002.
To query the node number of a file index, use LS-I.
The following is a test Program :
# Include <stdio. h>
# Include <sys/types. h>
# Include <sys/IPC. h>
# Define ipckey 0x11
Int main (void)
{
Int I = 0;
For (I = 1; I <256; ++ I)
Printf ("Key = % x \ n", ftok ("/tmp", I ));
Return 0;
}
After obtaining the key, you can use the key as the key value for inter-process communication in a certain method, such as shmget shared memory.