9

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?

alk
  • 69,737
  • 10
  • 105
  • 255
asc99c
  • 3,815
  • 3
  • 31
  • 54

2 Answers2

8

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

Hasturkun
  • 35,395
  • 6
  • 71
  • 104
  • 3
    I'd say "you **do** want". SysV IPC is an abomination. – Jan Hudec Sep 07 '11 at 12:15
  • Using the filesystem as a globally visible namespace is an excellent idea. SYSV probably did it wrong by putting shm into an isolated namespace. But hey! they invented it... – wildplasser Sep 07 '11 at 12:59
  • Thanks! I've just rewritten the application to use shm_open/mmap instead of shmget/shmat. It has certainly got as far as compiling, restarting, and the shared memory database appears to be working. A lot more testing to go through, but definitely looks like a neat solution. – asc99c Sep 07 '11 at 14:20
1

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.

wildplasser
  • 43,142
  • 8
  • 66
  • 109