File: rawfilelock_unix.go

package info (click to toggle)
golang-github-containers-storage 1.59.1%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 4,184 kB
  • sloc: sh: 630; ansic: 389; makefile: 143; awk: 12
file content (49 lines) | stat: -rw-r--r-- 858 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//go:build !windows

package rawfilelock

import (
	"time"

	"golang.org/x/sys/unix"
)

type fileHandle uintptr

func openHandle(path string, mode int) (fileHandle, error) {
	mode |= unix.O_CLOEXEC
	fd, err := unix.Open(path, mode, 0o644)
	return fileHandle(fd), err
}

func lockHandle(fd fileHandle, lType LockType, nonblocking bool) error {
	fType := unix.F_RDLCK
	if lType != ReadLock {
		fType = unix.F_WRLCK
	}
	lk := unix.Flock_t{
		Type:   int16(fType),
		Whence: int16(unix.SEEK_SET),
		Start:  0,
		Len:    0,
	}
	cmd := unix.F_SETLKW
	if nonblocking {
		cmd = unix.F_SETLK
	}
	for {
		err := unix.FcntlFlock(uintptr(fd), cmd, &lk)
		if err == nil || nonblocking {
			return err
		}
		time.Sleep(10 * time.Millisecond)
	}
}

func unlockAndCloseHandle(fd fileHandle) {
	unix.Close(int(fd))
}

func closeHandle(fd fileHandle) {
	unix.Close(int(fd))
}