Which file should be passed as an argument to pathname ftok ()

Specified in ftok () manual

key_t ftok(const char *pathname, int proj_id); 

The ftok () function uses the identifier of a file with a name at a given path (which should refer to an existing accessible file) ...

I am confused about const char *pathname .

What would be the best practice for this? On my current system, I can go through "/home/Andrew/anyfile" , but it is not possible that other systems on which my program should work will have this file.

How can I use "/etc/hosts/" or "/etc/inittab" because I'm sure that all such systems will have these two files? Is that a good idea? Could this cause any problems?

I do not want to ask the user to enter the file name at run time or pass the file name as a command line argument.

Is there any other other and better way to resolve pathname ?
Which method is the best and reliable?

Thank you for your time.

+7
c linux queue ipc ftok
source share
3 answers

Well, usually you should use the file associated with the application itself.

For example, we had an application that loaded a configuration file into shared memory (in a parsable, efficient way — think of an XML file that was converted to memory structures with quick pointers, etc.), and we created a shared memory segment from ftok obtained from the configuration file itself.

In the worst case, if you do not have configuration files for your application, try using the executable itself. You can be sure that it exists in the system somewhere (since you run it).

You are also not limited to files, you can use /etc yourself or /tmp or even / if you need.

I say "if necessary" because it is a little dangerous. Calling ftok will give you a unique key based on the specifications of your file and your identifier. If you use your own file, for example /etc/andrew.conf , you can be sure that you will not encounter any other ftok listed key.

However, if you and everyone else decided to use /tmp as part of the file specification, then the only difference is the identifier. Therefore, it is much easier to get a collision with other keys.

What I always did was use the file specification as a truly unique value for my application, and then just use the identifier for the specific thing I want to create.

So, if I need 27 semaphores and 15 blocks of shared memory, they all use /etc/pax.conf as a file specification and identifiers from 1 to 42 (and my application knows which identifier refers to which object).

+12
source share

Perhaps it is best to use argv [0] from one of your executables. The manual page says

 The resulting value is the same for all pathnames that name the same file, ... 

therefore, you should be safe, even if your executable is sometimes called through a symbolic link or so.

+2
source share

You can dynamically create char * for a path based on a configuration file or command line parameter, etc.

Just pass this char * to the function.

+1
source share

All Articles