0

I have an existing code in system that uses ftok() to generate key based on the file name and a zero passed to it. The code was working fine on 32 bit but starts complaining randomly when moved to 64 bits. On researching more , I found that this is mostly because of the lower signicant bits are zero and shmopen() could be a better alternative. Let me know does shmopen() is safe from key collisions? Are there any better way to avoid key collisions?

key = ftok(filename,0);
Sachin
  • 20,805
  • 32
  • 86
  • 99
  • I suppose that you mean `shm_open`? The "key" there is just what makes it unique, so you'd have take care of that yourself. You could check if a given name is already taken by using the flags `O_CREAT | O_EXCL`. – Jens Gustedt May 20 '13 at 07:45

1 Answers1

1

From the POSIX specification:

The ftok() function shall return the same key value for all paths that name the same file, when called with the same id value, and return different key values when called with different id values or with paths that name different files existing on the same file system at the same time. It is unspecified whether ftok() shall return the same key value when called again after the file named by path is removed and recreated with the same name.

So calling the function with the same path and id will return the same key. If you want a different key for the same path then you need to change the id.

And yes, passing zero as the id leads to unspecified behavior, so you should not do that.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • does changing the last argument to other than zero guarantees generation iof unique keys? Do we have a better alternative, i just google and found that shmopen() is, but i am not sure about it. – Sachin May 20 '13 at 07:31
  • @SachinChourasiya It's clear in the specification, changing the id argument will change the returned key. Also, I guess you mean [`shm_open`](http://pubs.opengroup.org/onlinepubs/009695399/functions/shm_open.html) (note the underscore)? If you're going to use shared memory then yes I recommend you use the POSIX variant (`shm_open`) before the old SYSV variant (`ftok`/`shmget` etc.). – Some programmer dude May 20 '13 at 07:47
  • Yup, i mean shmopen(). Thanks Joachim. I will try using a different integer to get the unique key id. – Sachin May 20 '13 at 08:03