I want to replicate this code part that used to convert file to key in my java project in order to access SharedMemory data.
so the code in c looks like that:
key_t ftok(const char *path, int id)
{
struct stat st;
if (stat(path, &st) < 0) return -1;
int inode = st.st_ino;
int dev = st.st_dev;
return ((st.st_ino & 0xffff) | ((st.st_dev & 0xff) << 16) | ((id & 0xff) << 24));
}
and with the use of chatgpt I got this code part, but for some reason the data in the inode and dev are not the same, so I guess that I cant access the stat properties of a specific file.. I could be wrong.
This is the Java code:
try {
Path absolutePath = Paths.get(path).toAbsolutePath();
BasicFileAttributes attributes = Files.readAttributes(absolutePath, BasicFileAttributes.class);
int st_ino = (int) (attributes.fileKey().hashCode());
int st_dev = (int) ((attributes.fileKey().hashCode() >> 16));
return (st_ino & 0xFFFF) | ((st_dev & 0xFF) << 16);
} catch (Exception e) {
return -1;
}
the value of the numbers in the st_ino and st_dev are close, but no the exact copy
I've tried to use BasicFileAttributes to get the same result but unfortunately the numbers are not the same.
Edit: Thanks for the responses and all the clarifications on the subject. I read what Stephen C did and I did something like this:
Path absolutePath = Paths.get(path).toAbsolutePath();
BasicFileAttributes attributes = Files.readAttributes(absolutePath, BasicFileAttributes.class);
String dev_ino_string = attributes.fileKey().toString();
int st_ino = extractValue(dev_ino_string, "ino");
int st_dev = extractValue(dev_ino_string, "dev");
(extractValues just get me the value from the toString)
to string response look like this:(dev=10302,ino=121896961)
and when I call attributes.fileKey().toString() I get this result:
st_dev = 66306
st_ino = 121896961
now it's a bit weird that the dev that i get is not the same in the tostring so I'll keep digging into it and look for an answer.
Edit 2:
This is what I see when I evaluate

And I cant simply extract the values with:
attributes.fileKey().st_dev
is there a way to bypass it and get the values?
OK ... I see what you are attempting.
In Java 11, the
hashCode()method for aUnixFileKeyreturns:... and I guess you are trying to extract the
st_devandst_inovalues from the returned value.But it won't work. That is not a reversible computation.
If you want to extract the
st_devandst_inofrom aUnixFileKey, you will need to break abstraction so that you can access the values of the fields. This can be done using reflection ... albeit that it is getting increasingly difficult to do this.Another alternative would be to parse the
Stringreturned by thetoString()method which (in Java 11) is formed as follows:Note that either way you do this is going to make your code dependent on (unspecified) implementation details of a JDK internal class. In theory it could break from one Java version to the next. (These details appear to be unchanged from Java 7 to 17, but YMMV.)