Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ftok() collisions

I am using ftok() to generate identifiers for shared memory segments used by a C application. I am having problems, where on one box I am getting collisions with the identifiers used by root. I can fix it in this instance by hacking the code, but I would like a more robust solution.

The application is installed into its own logical volume, and the path supplied to ftok is the binaries directory for the application (within that lv). The IDs supplied start at 1 and there are usually half a dozen or so.

I've tracked down that ftok will do something like this:

(id & 0xff) << 24 | (st.st_dev & 0xff) << 16 | (st.st_ino & 0xffff)

The combination of st.st_dev / st.st_ino should be very unique. But I've seen across a number of boxes, the least significant bit of st_dev is often 0 (i.e. st_dev numbers are generally multiples of 256). And because the binary directory is in a logical volume, there is no guarantee that the inode number will be different from something root uses.

Is there a good way around this - a better alternative to ftok, or a way of setting up machines such that the st_dev numbers will be of more use to ftok?

like image 913
asc99c Avatar asked Sep 07 '11 11:09

asc99c


2 Answers

You may want to consider using POSIX shared memory (via shm_open), which doesn't suffer from this sort of key collision

like image 57
Hasturkun Avatar answered Nov 10 '22 19:11

Hasturkun


Your application should always be able to deal with key collisions. A key could be in use by another unrelated process. But you could try to create your own version of ftok(), using more relevant bits.

In theory any application needs only one "master" key, pointing to a "scoreboard" where the other keys can be found. Publicizing the masterkey on the filesystem might be a good idea. Restart after a crash will always be a problem.

like image 38
wildplasser Avatar answered Nov 10 '22 20:11

wildplasser