What is the formula used to produce a key that ftok() produces? ftok is a Linux function for creating keys for SYSTEM V IPC.
Asked
Active
Viewed 833 times
2
-
1Read ftok manual page. – IMParasharG Feb 02 '19 at 11:58
-
31. Wouldn't that depend on which libc you're using? 2. Why do you care? – melpomene Feb 02 '19 at 12:00
-
On Linux, most implementations of `libc` are free software. So study the source code of the particular `libc` you are using, probably [glibc](https://www.gnu.org/software/libc/) ore perhaps [musl-libc](http://musl-libc.org/) – Basile Starynkevitch Feb 02 '19 at 12:02
-
1`ftok()` is not Linux-specific. It is a standard part of the SysV IPC suite. – John Bollinger Feb 02 '19 at 13:24
-
*ftok is a Linux function for creating keys for SYSTEM V IPC.* And a horrible one at that. Picking a random number and hoping it's unique, with no information on already-used keys on the system, is worse than picking a random number yourself. At least you can actually collect information on what keys are already in use. – Andrew Henle Feb 02 '19 at 15:22
2 Answers
5
key_t
ftok (const char *pathname, int proj_id)
{
struct stat64 st;
key_t key;
if (__xstat64 (_STAT_VER, pathname, &st) < 0)
return (key_t) -1;
key = ((st.st_ino & 0xffff) | ((st.st_dev & 0xff) << 16)
| ((proj_id & 0xff) << 24));
return key;
}
I.e. it's creating a 32-bit key_t
by taking the upper 8 bits from the lower 8 bits of proj_id
, the second upper 8 bits from the lower 8 bits of the device number of the provided pathname
, and the lower 16 bits from the lower 16 bits of the inode number of the provided pathname
.
musl libc uses the same algorithm:
key_t ftok(const char *path, int id)
{
struct stat st;
if (stat(path, &st) < 0) return -1;
return ((st.st_ino & 0xffff) | ((st.st_dev & 0xff) << 16) | ((id & 0xffu) << 24));
}

melpomene
- 84,125
- 8
- 85
- 148
0
The ftok() source code in glibc library is :
#include <sys/ipc.h>
#include <sys/stat.h>
key_t
ftok (const char *pathname, int proj_id)
{
struct stat64 st;
key_t key;
if (__xstat64 (_STAT_VER, pathname, &st) < 0)
return (key_t) -1;
key = ((st.st_ino & 0xffff) | ((st.st_dev & 0xff) << 16)
| ((proj_id & 0xff) << 24));
return key;
}
Other functions are available here too.

moinmaroofi
- 359
- 1
- 12
-
1What's the point of this answer? It just repeats what's in my answer (which is older by an hour) and links to a third-party site instead of the official glibc code repository. – melpomene Feb 02 '19 at 14:45
-
I agree with melpomene. Please don't waste time bytes and internet band for useless things. – linuxfan says Reinstate Monica Feb 02 '19 at 15:48