How to test in two paths are hard linkable?

112 views Asked by At

I have file paths in one side and their new paths where I want to duplicate them.

How to test whether they can be simply hardlinked or they should be copied?

2

There are 2 answers

1
Nemo On BEST ANSWER

Step 1: Call link.

Step 2: If it returns -1 with errno set to EXDEV, then make a copy.

[update]

In general, there is no portable (and reliable) way to answer this question. The closest you can get, I think, is to call statvfs for the source and destination and then compare the f_fsid fields of the statvfs structures.

Unfortunately, POSIX does not guarantee anything in particular about the f_fsid field. This test should work on Linux unless maybe you are asking about NFS-mounted filesystems...

0
Basile Starynkevitch On

Nemo's answer is indeed the simplest solution: try the link(2) syscall.

If you only want to know if the path are hard linkable without even attempting the link(2) syscall, you could find their filesystem e.g. using statfs(2), check that they are on the same filesystem, and check that the filesystem's type is good enough.