ftok: Resource temporarily unavailable

Viewed 152

I'm developing app under c that needs to comunicate via shared memory. I need to generate key, by some fields in my app, so I just converted them to int and call ftok, but it doesn't work and I dont know why.

Code that causes error:

int proj_id = 3001; // it's calculated by app, basicly it just convert a few fields into unique int for example 3001
key_t key;
if((key = ftok(".", proj_id)) < 0);
{
   perror("ftok");
   return -1;
}

output : ftok: Resource temporarily unavailable

But constantly i run into this issue. Do you have any idea why and how to solve it? Thanks in an advance! ;)

1 Answers

The error check should be:

if ((key = ftok(".", proj_id)) == (key_t)-1) //... error

Negative keys can be (and are on Linux) valid (https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftok.html).

You must be getting a negative key and perror then just prints the last (unrelated) errno you had, which in your case just happens to be EAGAIN.

In most cases where POSIX prescribes that a -1 be returned on error, the < 0 check is sufficient (and actually generates slightly better assembly than a == -1 check), because the successfully returned values are then usually limited to nonnegative numbers. However, there are a few exceptions where you need an exact == -1 check, and ftok is one of those exceptions.

Additionally, as KamilCuk points out, using a file path as opposed to a directory path might increase your code's portability as the posix spec for ftok seems a bit ambiguous as to whether directory paths are allowed or not (directories are "files" under Unixes, but it's not clear whether the spec wants the term "file path" to encompass directory paths as well).

Related