Pages

Wednesday, June 8, 2011

keys

Keys

Unix requires a key of type key_t defined in file sys/types.h for requesting resources such as shared memory segments, message queues and semaphores. A key is simply an integer of type key_t; however, you should not use int or long, since the length of a key is system dependent.
There are three different ways of using keys, namely:
  1. a specific integer value (e.g., 123456)
  2. a key generated with function ftok()
  3. a uniquely generated key using IPC_PRIVATE (i.e., a private key).
The first way is the easiest one; however, its use may be very risky since a process can access your resource as long as it uses the same key value to request that resource. The following example assigns 1234 to a key:

key_t     SomeKey;

SomeKey = 1234;
The ftok() function has the following prototype:

key_t  ftok(
            const char *path,      /* a path string       */
            int        id          /* an integer value    */
           );   
Function ftok() takes a character string that identifies a path and an integer (usually a character) value, and generates an integer of type key_t based on the first argument with the value of id in the most significant position. For example, if the generated integer is 35028A5D16 and the value of id is 'a' (ASCII value = 6116), then ftok() returns 61028A5D16. That is, 6116 replaces the first byte of 35028A5D16, generating 61028A5D16.Thus, as long as processes use the same arguments to call ftok(), the returned key value will always be the same. The most commonly used value for the first argument is ".", the current directory. If all related processes are stored in the same directory, the following call to ftok() will generate the same key value:

#include  <sys/types.h>
#include  <sys/ipc.h>

key_t     SomeKey;

SomeKey = ftok(".", 'x');
After obtaining a key value, it can be used in any place where a key is required. Moreover, the place where a key is required accepts a special parameter, IPC_PRIVATE. In this case, the system will generate a unique key and guarantee that no other process will have the same key. If a resource is requested with IPC_PRIVATE in a place where a key is required, that process will receive a unique key for that resource. Since that resource is identified with a unique key unknown to the outsiders, other processes will not be able to share that resource and, as a result, the requesting process is guaranteed that it owns and accesses that resource exclusively.

No comments:

Post a Comment