github.com/petermattis/pebble@v0.0.0-20190905164901-ab51a2166067/vfs/file_lock_unix.go (about) 1 // Copyright 2014 The LevelDB-Go and Pebble Authors. All rights reserved. Use 2 // of this source code is governed by a BSD-style license that can be found in 3 // the LICENSE file. 4 5 // +build darwin dragonfly freebsd linux netbsd openbsd solaris 6 7 package vfs 8 9 import ( 10 "io" 11 "os" 12 "syscall" 13 ) 14 15 // lockCloser hides all of an os.File's methods, except for Close. 16 type lockCloser struct { 17 f *os.File 18 } 19 20 func (l lockCloser) Close() error { 21 return l.f.Close() 22 } 23 24 func (defaultFS) Lock(name string) (io.Closer, error) { 25 f, err := os.Create(name) 26 if err != nil { 27 return nil, err 28 } 29 spec := syscall.Flock_t{ 30 Type: syscall.F_WRLCK, 31 Whence: io.SeekStart, 32 Start: 0, 33 Len: 0, // 0 means to lock the entire file. 34 Pid: int32(os.Getpid()), 35 } 36 if err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &spec); err != nil { 37 f.Close() 38 return nil, err 39 } 40 41 return lockCloser{f}, nil 42 }