blob: 01790f91fa2587b45050fb33683b9521f8612fba (
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
|
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/vt.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
// check if argument is tty[0-9]
static bool is_vt_basename(const char *s) {
return !strncmp(s, "tty", 3) && isdigit(s[3]);
}
// return the number of the active virtual terminal or -1 on error
static int get_active_vt() {
int dfd = open("/dev", O_RDONLY | O_DIRECTORY);
if (dfd < 0) {
perror("open /dev");
return 1;
}
DIR *d = fdopendir(dfd);
if (!d) {
perror("fdopendir");
close(dfd);
return 1;
}
int active_vt = -1;
struct dirent *ent;
while ((ent = readdir(d)) != NULL) {
if (!is_vt_basename(ent->d_name))
continue;
int fd = openat(dfd, ent->d_name, O_RDONLY | O_NONBLOCK);
if (fd < 0)
continue;
struct vt_stat state;
if (ioctl(fd, VT_GETSTATE, &state) == 0) {
active_vt = state.v_active;
close(fd);
break;
}
close(fd);
}
closedir(d);
return active_vt;
}
int main(void) {
int active_vt = get_active_vt();
if (active_vt < 0) {
fprintf(stderr, "Could not determine active VT\n");
return 1;
}
printf("%d\n", active_vt);
return 0;
}
|