One of the problems with SysV IPC methods is the need to choose a unique
identifier for our processes. How can we make sure that the identifier of a
semaphore in our project won't collide with the identifier of a semaphore in
some other program installed on the system?
A D V E R T I S E M E N T
To help with that, the ftok() system call was introduced. This
system call accepts two parameters, a path to a file and a character, and
generates a more-or-less unique identifier. It does that by finding the "i-node"
number of the file (more or less the number of the disk sector containing this
file's information), combines it with the second parameter, and thus generates
an identifier, that can be later fed to semget, shmget()
or msgget(). Here is how to use ftok():
/* identifier returned by ftok() */
key_t set_key;
/* generate a "unique" key for our set, using the */
/* directory "/usr/local/lib/ourprojectdir". */
set_key = ftok("/usr/local/lib/ourprojectdir", 'a');
if (set_key == -1) {
perror("ftok: ");
exit(1);
}
/* now we can use 'set_key' to generate a set id, for example. */
sem_set_id = semget(set_key, 1, IPC_CREAT | 0600);
.
.
One note should be taken: if we remove the file and then re-create it, the
system is very likely to allocate a new disk sector for this file, and thus
activating the same ftok call with this file will generate a
different key. Thus, the file used should be a steady file, and not one that is
likely to be moved to a different disk or erased and re-created.