I
I
izac2017-10-13 15:21:34
go
izac, 2017-10-13 15:21:34

Is the file in use by another process?

I started learning Golang and decided to write a program that monitors the folder (I use https://github.com/howeyc/fsnotify this utility), but at the moment when we determine that the new file was created in the folder I am monitoring it, as I understand it , this utility opens this file, and when trying to open the file, we get an error that the file cannot be opened because it is being used by another process

func main(){
  watcher, err := fsnotify.NewWatcher()
    if err != nil {
        log.Fatal(err)
    }

    done := make(chan bool)

    // Process events
    go func() {
        for {
            select {
            case ev := <-watcher.Event:
                if ev.IsCreate() == true {
                	time.Sleep(100 * time.Millisecond)
                	 file,err := os.OpenFile(path,os.O_RDWR|os.O_EXCL,0755)
                }
            case err := <-watcher.Error:
                log.Println("error:", err)
            }
        }
    }()

    err = watcher.Watch("test")
    if err != nil {
        log.Fatal(err)
    }

    <-done

    watcher.Close()
}

the code shows that a "crutch method" with a slip was made, but I think that this is not correct and therefore I want to know how to do it normally, I know that there is such an opportunity as defer but I don’t know how it can be used with if

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2017-10-13
@pav5000

In your code you are waiting for the file to be created, once it is created you open it and don't close it. Therefore, it writes to you that the file is being occupied by another process.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question