summaryrefslogtreecommitdiff
path: root/util/sbase/flock.c
blob: fc2b6ed6e06140ef447820a96be28cbd76c425fd (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
/* See LICENSE file for copyright and license details. */
#include <sys/file.h>
#include <sys/wait.h>

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

#include "util.h"

static void
usage(void)
{
	eprintf("usage: %s [-nosux] file cmd [arg ...]\n", argv0);
}

int
main(int argc, char *argv[])
{
	int fd, status, savederrno, flags = LOCK_EX, nonblk = 0, oflag = 0;
	pid_t pid;

	ARGBEGIN {
	case 'n':
		nonblk = LOCK_NB;
		break;
	case 'o':
		oflag = 1;
		break;
	case 's':
		flags = LOCK_SH;
		break;
	case 'u':
		flags = LOCK_UN;
		break;
	case 'x':
		flags = LOCK_EX;
		break;
	default:
		usage();
	} ARGEND

	if (argc < 2)
		usage();

	if ((fd = open(*argv, O_RDONLY | O_CREAT, 0644)) < 0)
		eprintf("open %s:", *argv);

	if (flock(fd, flags | nonblk)) {
		if (nonblk && errno == EWOULDBLOCK)
			return 1;
		eprintf("flock:");
	}

	switch ((pid = fork())) {
	case -1:
		eprintf("fork:");
	case 0:
		if (oflag && close(fd) < 0)
			eprintf("close:");
		argv++;
		execvp(*argv, argv);
		savederrno = errno;
		weprintf("execvp %s:", *argv);
		_exit(126 + (savederrno == ENOENT));
	default:
		break;
	}
	if (waitpid(pid, &status, 0) < 0)
		eprintf("waitpid:");

	if (close(fd) < 0)
		eprintf("close:");

	if (WIFSIGNALED(status))
		return 128 + WTERMSIG(status);
	if (WIFEXITED(status))
		return WEXITSTATUS(status);

	return 0;
}