summaryrefslogtreecommitdiffstats
path: root/runfd.c
blob: 59b9d8c05c0474b51e63f45a0222a0b805c56e71 (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
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

/**
 * NOTE: requires fdescfs to be mounted to run interpreted files (starting with #!)
 */

#define DEFAULT_FD 3

char *args[] = { "batchrun", NULL };

void
set_async(int fd, int on)
{
	int flags;

	if ((flags = fcntl(fd, F_GETFL)) == -1)
		err(1, "fcntl()");

	if (on) {
		flags |= O_NONBLOCK;
	} else {
		flags &= ~O_NONBLOCK;
	}

	if (fcntl(fd, F_SETFL, flags) == -1)
		err(1, "fcntl()");
}

int
main(int argc, char **argv)
{
	char buf[2], *end = NULL;
	ssize_t ret;
	int tries = 0, fd = DEFAULT_FD;

	if (argc > 1) {
		fd = strtol(argv[1], &end, 10);

		if (end == argv[1])
			errx(1, "Filedescriptor supplied (\"%s\") is not a number", argv[1]);
	}

	set_async(fd, 1);

retry:
	if (tries++ >= 3)
		errx(1, "Failed to read file header");

	ret = pread(fd, buf, sizeof(buf), 0);
	if (ret == 2) {
		if (strncmp(buf, "#!", 2) != 0) {
			fcntl(fd, F_SETFD, FD_CLOEXEC);
		}
	} else if (ret == -1) {
		if (errno == EINTR)
			goto retry;
		else if (errno != EAGAIN)
			err(1, "pread()");
	} else if (ret != 0) {
		goto retry;
	}

	set_async(fd, 0);

	fexecve(fd, args, NULL);
	err(1, "fexecve()");
}