| 1 | // Copyright 2014 The LevelDB-Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // +build darwin dragonfly freebsd linux netbsd openbsd |
| 6 | |
| 7 | package filelock |
| 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 Lock(name string) (io.Closer, error) { |
| 25 | f, err := os.Create(name) |
| 26 | if err != nil { |
| 27 | return nil, err |
| 28 | } |
| 29 | |
| 30 | /* |
| 31 | Some people tell me FcntlFlock does not exist, so use flock here |
| 32 | */ |
| 33 | if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { |
| 34 | f.Close() |
| 35 | return nil, err |
| 36 | } |
| 37 | |
| 38 | // spec := syscall.Flock_t{ |
| 39 | // Type: syscall.F_WRLCK, |
| 40 | // Whence: int16(os.SEEK_SET), |
| 41 | // Start: 0, |
| 42 | // Len: 0, // 0 means to lock the entire file. |
| 43 | // Pid: int32(os.Getpid()), |
| 44 | // } |
| 45 | // if err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &spec); err != nil { |
| 46 | // f.Close() |
| 47 | // return nil, err |
| 48 | // } |
| 49 | |
| 50 | return lockCloser{f}, nil |
| 51 | } |