Converting string to key_t

2.9k views Asked by At

How is it possible to convert a string to a key_t, in order to use it for creating a shared memory segment by using shmget?

This is because the key for mapping the shared memory is being transmitted over TCP/IP.

Thanks in advance!

2

There are 2 answers

4
alk On BEST ANSWER

The key is created by a call to ftok(). The latter uses a file path and an 8bit value to do so.

For the same file path and the same 8bit value ftok() (re-)creates the same key.

So transfer the file path and the 8bit value (typically another char) and let the receiver call ftok() on the values received. This will create the same key as the sender uses.

From ftok()'s documentation:

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 significant 8 bits of proj_id (which must be nonzero) to generate a key_t type System V IPC key, suitable for use with msgget(2), semget(2), or shmget(2).

The resulting value is the same for all pathnames that name the same file, when the same value of proj_id is used. The value returned should be different when the (simultaneously existing) files or the project IDs differ.

2
Felix Frank On

Make sure the receiver interprets the data in the same way that the sender put them on the line.

E.g., if the sender does

char buf[32];
*((key_t*)buf) = data;

and sends the 32 byte buffer over the net, the receiver should read them into a matching buffer and extract the key_t using

data = *((key_t*)buf);