I'm trying to lock one file when there's one process writing it. When another process tries reading the file, it needs to make sure that no process is writing on it. The idea is that when the write process dies before unlocking the file, and another read process can detect this and deletes this semi-finished file.
To do that, I built such a FileLock structure:
type FileLock struct {
filePath string
f *os.File
}
func (l *FileLock) Lock() error {
if l.f == nil {
f, err := os.OpenFile(l.filePath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0200)
if err != nil {
return err
}
l.f = f
}
err := syscall.Flock(int(l.f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if err != nil {
return fmt.Errorf("cannot flock file %s - %s", l.filePath, err)
}
return nil
}
func (l *FileLock) Unlock() error {
defer l.f.Close()
return syscall.Flock(int(l.f.Fd()), syscall.LOCK_UN)
}
Before writing to this localfile, I lock it. And unlock when the write is finished:
func downloadFile(response *http.Response, filePath string) error {
output, _ := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0200)
localFileLock := &FileLock{filePath: filePath, f: output}
// Lock the file before writing.
if err := localFileLock.Lock(); err != nil {
return err
}
if _, err := io.Copy(output, response.Body); err != nil {
return fmt.Errorf("problem saving %s to %s: %s", response.Request.URL, filePath, err)
}
// Unlock the file after writing.
if err := localFileLock.Unlock(); err != nil {
return err
}
return nil
}
But for another process, how to check if that file is locked?
Thanks!