How to determine the file name change of an open file in the Golang

Using Go, I wrote a small utility that partially needs to notice if the file of the open file changes. The code below illustrates the approach I tried:

package main import "os" import "fmt" import "time" func main() { path := "data.txt" file, _ := os.Open(path) for { details, _ := file.Stat() fmt.Println(details.Name()) time.Sleep(5 * time.Second) } } 

It just starts an endless loop by running file.Stat() to get file information every 5 seconds and then print the name. However, despite the change in the file name when it is launched, the output of the above does not change.

replacing details.Name() with details.Size() , however notice changes in file size.

Is this just a bug in my version of Go, or am I just doing something wrong? I cannot find mention of such a problem anywhere.

I run this on a Mac with Go version 1.1.1 (darwin / amd64).

Thanks for any answers :)

+6
source share
2 answers

On Unix-like operating systems, as soon as you open a file, it is no longer bound to a name. The file descriptor that you receive is attached only to the inode of the file that you open. All file metadata is associated with inode. There is no easy way to get the file name from the inode, so you cannot, unless your operating system provides special tools for this.

Also: What file name do you want to watch? A file may have several names or no name at all (for example, a typical temporary file).

The only thing I think you can do is:

  • Open the file, remember the file name
  • periodically call Stat in the file name to see if the inode index matches
  • If the inode index is different, your file has been moved

This, however, does not give you a new file name. This is not possible to do portable.

+4
source

Alas, it is quite difficult to find the name of the open file in general.

All file.Name() does this ( see docs )

 // Name returns the name of the file as presented to Open. func (f *File) Name() string { return f.name } 

You can check this question for some ideas: Getting the file name from a file descriptor in C. The answers have solutions for Linux, Windows, and Mac.

+2
source

Source: https://habr.com/ru/post/954892/


All Articles