aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/vlib/os/filelock/lib_nix.c.v
blob: 1af99165f8da08ba26b94c422de3d2c45e0d47e9 (plain)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
module filelock

import time

#include <sys/file.h>

fn C.unlink(&char) int
fn C.open(&char, int, int) int
fn C.flock(int, int) int

[unsafe]
pub fn (mut l FileLock) unlink() {
	if l.fd != -1 {
		C.close(l.fd)
		l.fd = -1
	}
	C.unlink(&char(l.name.str))
}

pub fn (mut l FileLock) acquire() ?bool {
	if l.fd != -1 {
		// lock already acquired by this instance
		return false
	}
	fd := open_lockfile(l.name)
	if fd == -1 {
		return error('cannot create lock file $l.name')
	}
	if C.flock(fd, C.LOCK_EX) == -1 {
		C.close(fd)
		return error('cannot lock')
	}
	l.fd = fd
	return true
}

pub fn (mut l FileLock) release() bool {
	if l.fd != -1 {
		unsafe {
			l.unlink()
		}
		return true
	}
	return false
}

pub fn (mut l FileLock) wait_acquire(s int) ?bool {
	fin := time.now().add(s)
	for time.now() < fin {
		if l.try_acquire() {
			return true
		}
		C.usleep(1000)
	}
	return false
}

fn open_lockfile(f string) int {
	mut fd := C.open(&char(f.str), C.O_CREAT, 0o644)
	if fd == -1 {
		// if stat is too old delete lockfile
		fd = C.open(&char(f.str), C.O_RDONLY, 0)
	}
	return fd
}

pub fn (mut l FileLock) try_acquire() bool {
	if l.fd != -1 {
		return true
	}
	fd := open_lockfile('$l.name')
	if fd != -1 {
		err := C.flock(fd, C.LOCK_EX | C.LOCK_NB)
		if err == -1 {
			C.close(fd)
			return false
		}
		l.fd = fd
		return true
	}
	return false
}