Last active
July 15, 2022 03:37
-
-
Save m1lkweed/3ecb39025a0f16810fe7b7b006e63e72 to your computer and use it in GitHub Desktop.
Returns true when running under a TTY, false under a VT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <fcntl.h> | |
#include <errno.h> | |
#include <unistd.h> | |
#include <stdbool.h> | |
#include <linux/kd.h> | |
#include <sys/ioctl.h> | |
static int is_a_console(int fd){ | |
char arg = 0; | |
return ((ioctl(fd, KDGKBTYPE, &arg) == 0) && ((arg == KB_101) || (arg == KB_84))); | |
} | |
static int open_a_console(const char *fnam){ | |
int fd = open(fnam, O_RDWR); | |
if(fd < 0 && errno == EACCES) | |
fd = open(fnam, O_WRONLY); | |
if(fd < 0 && errno == EACCES) | |
fd = open(fnam, O_RDONLY); | |
if(fd < 0) | |
return -1; | |
if(!is_a_console(fd)){ | |
close(fd); | |
return -1; | |
} | |
return fd; | |
} | |
int getfd(const char *fnam){ | |
int fd; | |
if(fnam){ | |
fd = open_a_console(fnam); | |
if(fd >= 0) | |
return fd; | |
return -1; | |
} | |
fd = open_a_console("/dev/tty"); | |
if(fd >= 0) | |
return fd; | |
fd = open_a_console("/dev/tty0"); | |
if(fd >= 0) | |
return fd; | |
fd = open_a_console("/dev/vc/0"); | |
if(fd >= 0) | |
return fd; | |
fd = open_a_console("/dev/console"); | |
if(fd >= 0) | |
return fd; | |
for(fd = 0; fd < 3; ++fd) | |
if(is_a_console(fd)) | |
return fd; | |
return -1; | |
} | |
bool is_real_tty(void){ | |
if(getfd(NULL) == -1) | |
return false; | |
else | |
return true; | |
} | |
int main(){ | |
puts(is_real_tty()?"Outputting to a TTY":"Outputting to a VT"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment