Check whether a file is a hard link
Asked Answered
K

3

6

How do you check whether a file is a hard link in Go? os.FileMode only has a mode for symlinks, not hard links.

I had an idea that unfortunately doesn't work:

package main

func main() {
    filename := os.Args[1]
    var hardlink bool
    link, _ := os.Readlink(filename)
    fi, _ := os.Stat(filename)
    mode := string(fi.Mode().String()[0])
    if link != "" && mode != "L" {
        hardlink = true
    }
    fmt.Printf("%v is hard link? %v\n", filename, hardlink)
}

This^ doesn't work because os.Readlink reads only symlinks, not hard links.

I found a somewhat related answer:
Counting hard links to a file in Go
But this answer shows how to find the number of hard links to a file, not whether a file itself is a hard link.

I'm guessing that the syscall package used in that answer or, better yet, the sys package has a way to test whether a file's a hard link. Does anyone know to do this? (I have trouble understanding those packages because they're so low-level.)

EDIT

I should add the reason why I'd like to check this. I'm trying to make a function to create a tar archive of a directory [using filepath.Walk()]. In this function, when I create the *tar.Header for a file, I set a value to *tar.Header.Typeflag.
For example, if fi is a file's *os.FileInfo variable and hdr is the *tar.Header variable for that file's place in a new tar archive, it looks like this:

if fi.Mode().IsDir() {
    hdr.Typeflag = tar.TypeDir
}

In the tar package, the modes for hard links and regular files are distinct, TypeLink and TypeReg, but this isn't the case in the os package. So running this won't set the correct Typeflag:

hdr.Mode = int64(fi.Mode())
Kyleekylen answered 8/8, 2015 at 2:14 Comment(3)
every regular file is a hard link. There's no difference between two hard links that point to the same inode, other than their name.Larocca
There's a reason the syscall to delete a file is called "unlink". (Also, The golang.org/x/sys package is just the syscall package plus updates, since the stdlib syscall is frozen)Larocca
I've honestly never thought of it that way before. That clears up a lot. I'm updating my answer to show the reason I want to check this.Kyleekylen
K
5

Figured it out from an example in Docker's source code:
https://github.com/docker/docker/blob/master/pkg/archive/archive.go
https://github.com/docker/docker/blob/master/pkg/archive/archive_unix.go

package main

import (
    "errors"
    "fmt"
    "log"
    "os"
    "syscall"
)

func main() {
    filename := os.Args[1]

    // 'os.Lstat()' reads the link itself.
    // 'os.Stat()' would read the link's target.
    fi, err := os.Lstat(filename)
    if err != nil {
        log.Fatal(err)
    }

    // https://github.com/docker/docker/blob/master/pkg/archive/archive_unix.go
    // in 'func setHeaderForSpecialDevice()'
    s, ok := fi.Sys().(*syscall.Stat_t)
    if !ok {
        err = errors.New("cannot convert stat value to syscall.Stat_t")
        log.Fatal(err)
    }

    // The index number of this file's inode:
    inode := uint64(s.Ino)
    // Total number of files/hardlinks connected to this file's inode:
    nlink := uint32(s.Nlink)

    // True if the file is a symlink.
    if fi.Mode()&os.ModeSymlink != 0 {
        link, err := os.Readlink(fi.Name())
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%v is a symlink to %v on inode %v.\n", filename, link, inode)
        os.Exit(0)
    }

    // Otherwise, for hardlinks:
    fmt.Printf("The inode for %v, %v, has %v hardlinks.\n", filename, inode, nlink)
    if nlink > 1 {
        fmt.Printf("Inode %v has %v other hardlinks besides %v.\n", inode, nlink, filename)
    } else {
        fmt.Printf("%v is the only hardlink to inode %v.\n", filename, inode)
    }
}
Kyleekylen answered 8/8, 2015 at 4:40 Comment(2)
BTW, you usually shouldn't save/use/refer-to just a files inode number; it's meaningless without also referring to the device (e.g. save/use/refer-to s.Dev, s.Ino instead). In particular for something like an archive tool walking a file tree it may cross a device/filesystem boundary and would need to distinguish different inodes from different devices that have the same inode number (e.g. by using a struct of s.Dev, s.Ino as a map/set key).Gillum
That's a really good point; forgetting to do that could be messy. I'll make sure to add that to my code. The link to the docker code has an example for that too, thankfullyKyleekylen
R
4

The term "hard link" is a bit of a misnomer. The way files work in most filesystems is that a given file (the thing identified by a path, like /foo) is actually just a pointer to a structure called an "inode." Inodes are the structures on disk that actually represent the contents and metadata of the file. When a file is a "hard link" to another file, it just means that they both point to the same inode. The system will keep track of the number of files pointing to a given inode, and make sure not to delete the inode until all files pointing to it have been deleted.

Thus, the question "is this file a hard link" doesn't really make sense. What does make sense is the question, "are these two files hard links to each other," or, more accurately, "are these two files pointers to the same inode." If you want to answer that question in Go, all you need is os.SameFile.

Ridings answered 8/8, 2015 at 2:41 Comment(5)
Thanks for explaining that! Yeah, the question's title should be more like "Check whether a file's inode has any other hardlinks". Unless anyone thinks I should change the title, I'll leave it as it is because otherwise the answers won't make much sense.Kyleekylen
Ah, gotcha. That I don't know. I'm not sure exactly how it's implemented under the hood, but I'd guess there's some kind of "points to me" counter on the inode, in which case there'd probably be some way to access it. But I'm not sure if that's correct, and even if it is, how you'd go about doing that.Ridings
Yup you're right! It's under syscall.Stat_t.Nlink and syscall.Stat_t.Ino. I found an example within Docker's source code showing how to get it. I made a quick, condensed example of it in the answer I posted.Kyleekylen
Can we say all files are hard link?Dynatron
Usually, when people say "hard link," they mean to imply two or more files that share the same inode. But you could certainly imagine defining the term "hard link" such that all files would be hard links. But then the term "hard link" wouldn't be very helpful, because it would basically mean the same thing as "file" :)Ridings
A
1

Files are hard links to inodes, you can have multiple hard links to inodes and the file system will not distinguish between them. If you have two files that point to the same inode on disk and remove one the file will still exist. Space is only reclaimed by the file system once all links to the inode have been deleted.

You can use ls -i to determine the index, and stats <path to file> to work out how many links to the inode there are in your file system.

Amphithecium answered 8/8, 2015 at 2:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.