Semaphore, message queue, and the function ftok for generating the ket_t key value in the shared memory.

Source: Internet
Author: User
Tags touch command

In System V, we often use the value of key_t to create or open semaphores, share memory and message queue. This is very important in the IPC environment. For example, the server creates a message queue and waits for the client to send a request. How to create or open an existing message queue? Generally, the path and Project ID (proj_id) used by the server are known, so the client can obtain the same key to open the message queue and perform operations. The following is the ftok usage prototype:

Ftok Function

The ftok function converts an existing path name and an integer identifier into a key_t value, which is called the IPC key:

# Include
# Include

Key_t ftok (const char * pathname, int proj_id );

The ftok function uses the identity of the file named by the given pathname (which must refer to an existing, accessible file) and the least signiicant 8 bits of proj_id (which must be nonzero) to generate a key_t Type System v ipc key.

This function combines the information exported from pathname with the low-order 8-bit ID into an integer IPC key.

# Include <sys/types. h>
# Include <sys/IPC. h>

Key_t ftok (const char * pathname, int proj_id );
1) pathname must exist in the system
2) pathname must be accessible by a process.
3) proj_id is an integer between 1 and. A typical value is an ASCII value.
When the execution is successful, a key_t value will be returned, otherwise-1 will be returned.

The following program demonstrates and prints how to use ftok and its corresponding values.

#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>int main( void ){    for ( int i = 1; i < 256; ++ i )        printf( "key = %ul/n", ftok( "/tmp", i  ) );    return 0;}


Based on the file (or directory) name specified by pathname and the number specified by the proj_id parameter, the ftok function generates a unique key value for the IPC object. In actual application, it is easy to understand that, when the proj_id is the same, as long as the file (or directory) name remains the same, to ensure that ftok returns consistent key values. However, this understanding is not completely correct and may leave a hidden trap for application development. Because ftok implementation has this risk, that is, when multiple processes accessing the same shared memory call the ftok function successively, if the file (or directory) specified by pathname) if it is deleted and re-created, the file system will assign the new I node information to this file (or directory) with the same name, so the ftok called by these processes can return normally, however, the obtained key values cannot be the same. The possible consequence is that these processes originally intended to access the same shared memory object. However, due to their different key values, the shared memory to which the process actually points is no longer consistent; if the shared memory is created, no errors are displayed during the entire application running process. However, data transmission by using a shared memory object cannot be achieved. Aix, Solaris, HP-UX are clear that after the key file is deleted and rebuilt, do not guarantee that the key value obtained through ftok unchanged, such as the AIX ftok man help information is declared: Attention: If the path parameter of the ftok subroutine names a file that has been removed while keys still refer to it, the ftok subroutine returns an error. if that file is then re-created, the ftok subroutine will probably return a key different from the original one.Linux does not provide a similar clear statement, but we can use the following simple routine test01.c to get the same validation:

<span style="background-color: rgb(255, 255, 255);">#include <stdio.h>#include <sys/ipc.h>void main(int argc, char* argv[]){if (argc !=2 ) {printf("Usage: %s KeyFile/n e.g. %s /tmp/mykeyfile/n", argv[0], argv[0]);return;}printf("Key generated by ftok:  0x%x/n", ftok(argv[1], 1));}</span>

Program the preceding routine to an executable program test01 on the Red Hat Enterprise Linux as Release 4 platform, and create a new file mykeyfile in the/tmp directory using the touch command, then generate the key value for the file:
# Touch/tmp/mykeyfile
Key generated by ftok: 0x101000b

Then, delete/tmp/mykeyfile and run the VI command to recreate the file and generate the key value again:
Key generated by ftok: 0x1010017

As you can see, although the file names are all/tmp/mykeyfile, they have not changed, but because of the file deletion and re-creation operations in the middle, the obtained key values are no longer the same. The most fundamental way to avoid such problems is to take measures to ensure that the files (or directories) specified by pathname are not deleted during the use of shared memory, and do not use files that may be deleted; alternatively, you can directly specify the key value without using ftok to obtain the key value.

Test results in centos5.2: If mykeyfile is created in the same way, the obtained key value remains unchanged. If the creation method is different, the key value is different.
Questions about ftok Functions
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)
The name of the file you specified when fname is used. ID is the sub-serial number.

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.

After the reconstruction file is deleted, the index node number is allocated by the operating system according to the current usage of the file system. Therefore, the index node number is different from the original one.

To ensure that the key_t value remains unchanged, ensure that the ftok file is not deleted or that a fixed key_t value is specified without ftok.

In addition, if multiple file systems exist on AIX and other operating systems, two files distributed on different file systems will have the same index node number, in this case, use ftok to operate the two files. As long as the ID parameter remains the same, the obtained key_t value is the same, causing Message Queue creation failure. However, this situation is rare.

Semaphore, message queue, and the function ftok for generating the ket_t key value in the shared memory.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.