From dd37240b95a8a165a8160af7e817b76d5308ce72 Mon Sep 17 00:00:00 2001 From: tv Date: Fri, 5 Dec 2025 10:31:25 +0100 Subject: activevt: init --- Makefile | 10 ++++++--- activevt.c | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 activevt.c diff --git a/Makefile b/Makefile index 14ffa64..cee9a29 100644 --- a/Makefile +++ b/Makefile @@ -2,13 +2,17 @@ PREFIX ?= /usr/local BINDIR ?= $(PREFIX)/bin CACHEDIR ?= $(PWD) +UTILS := activevt exec + +BUILT_UTILS := $(addprefix $(CACHEDIR)/,$(UTILS)) + .PHONY: all -all: $(CACHEDIR)/exec +all: $(BUILT_UTILS) .PHONY: install -install: $(CACHEDIR)/exec +install: $(BUILT_UTILS) mkdir -p $(BINDIR) - cp $(CACHEDIR)/exec $(BINDIR)/ + cp $^ $(BINDIR)/ $(CACHEDIR)/%: %.c gcc -Wall -Os -o $@ $< diff --git a/activevt.c b/activevt.c new file mode 100644 index 0000000..01790f9 --- /dev/null +++ b/activevt.c @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// 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; +} -- cgit v1.2.3