~nskaggs/+junk/xenial-test

« back to all changes in this revision

Viewing changes to src/github.com/juju/go4/lock/lock_freebsd.go

  • Committer: Nicholas Skaggs
  • Date: 2016-10-24 20:56:05 UTC
  • Revision ID: nicholas.skaggs@canonical.com-20161024205605-z8lta0uvuhtxwzwl
Initi with beta15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
Copyright 2013 The Go Authors
 
3
 
 
4
Licensed under the Apache License, Version 2.0 (the "License");
 
5
you may not use this file except in compliance with the License.
 
6
You may obtain a copy of the License at
 
7
 
 
8
     http://www.apache.org/licenses/LICENSE-2.0
 
9
 
 
10
Unless required by applicable law or agreed to in writing, software
 
11
distributed under the License is distributed on an "AS IS" BASIS,
 
12
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
13
See the License for the specific language governing permissions and
 
14
limitations under the License.
 
15
*/
 
16
 
 
17
package lock
 
18
 
 
19
import (
 
20
        "fmt"
 
21
        "io"
 
22
        "os"
 
23
        "syscall"
 
24
        "unsafe"
 
25
)
 
26
 
 
27
func init() {
 
28
        lockFn = lockFcntl
 
29
}
 
30
 
 
31
func lockFcntl(name string) (io.Closer, error) {
 
32
        fi, err := os.Stat(name)
 
33
        if err == nil && fi.Size() > 0 {
 
34
                return nil, fmt.Errorf("can't Lock file %q: has non-zero size", name)
 
35
        }
 
36
 
 
37
        f, err := os.Create(name)
 
38
        if err != nil {
 
39
                return nil, err
 
40
        }
 
41
 
 
42
        // This type matches C's "struct flock" defined in /usr/include/fcntl.h.
 
43
        // TODO: move this into the standard syscall package.
 
44
        k := struct {
 
45
                Start  int64 /* off_t starting offset */
 
46
                Len    int64 /* off_t len = 0 means until end of file */
 
47
                Pid    int32 /* pid_t lock owner */
 
48
                Type   int16 /* short lock type: read/write, etc. */
 
49
                Whence int16 /* short type of l_start */
 
50
                Sysid  int32 /* int   remote system id or zero for local */
 
51
        }{
 
52
                Start:  0,
 
53
                Len:    0, // 0 means to lock the entire file.
 
54
                Pid:    int32(os.Getpid()),
 
55
                Type:   syscall.F_WRLCK,
 
56
                Whence: int16(os.SEEK_SET),
 
57
                Sysid:  0,
 
58
        }
 
59
 
 
60
        _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, f.Fd(), uintptr(syscall.F_SETLK), uintptr(unsafe.Pointer(&k)))
 
61
        if errno != 0 {
 
62
                f.Close()
 
63
                return nil, errno
 
64
        }
 
65
        return &unlocker{f: f, abs: name}, nil
 
66
}