문제

It is mentioned in ftok() manual

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

The ftok() function uses the identity of the file named by the given pathname (which must refer to an existing, accessible file) ...

I am confused about const char *pathname.

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

How about I use "/etc/hosts/" or "/etc/inittab" because I am sure all such systems will have these two files? Is it a good idea? Can it cause any problem?

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

Is there any other different and better way to decide pathname?
Which way is the best and most reliable one?

Thanks for your time.

도움이 되었습니까?

해결책

Well, generally you would use a file associated with the application itself.

For example, we had an application which loaded a configuration file into shared memory (in a parsed efficiently accessible way - think of an XML file which has been turned into in-memory structures with fast pointers and so forth) and we created the shared memory segment from the ftok derived from the configuration file itself.

Worst case, if you have no configuration files for your application, try to use the executable itself. You can be pretty certain that it exists on the system somewhere (since you're running it).

You're also not restricted to files, you can use /etc itself or /tmp or even / if you must.

I say "if you must" because it's a little bit dangerous. The ftok call will give you a unique key based on your file spec and your ID. If you use your own file such as /etc/andrew.conf, you can be reasonably certain that you won't get a clash with any other ftok-returned key.

However, if you, and everyone else, decides to use /tmp as the file spec part then the only differentiator is the ID. Hence it's a lot easier to get a collision with other keys.

What I've always done is to use the file spec as a truly unique value for my application and then just use the ID for the particular thing I want to create.

So, if I need 27 semaphores and 15 shared memory blocks, they all use /etc/pax.conf as the file spec and the IDs from 1 to 42 (and my application knows what ID relates to what object).

다른 팁

Probably the best is to use argv[0] of one of your executables. The man page says

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

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

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

Just pass that char * into the function.

Use "." as the first parameter. It will send the current running directory to ftok.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top