Skip to content

Instantly share code, notes, and snippets.

@wmoxam
Created September 2, 2022 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wmoxam/59be6be5ef1b13f6c13e9d0d21b2c622 to your computer and use it in GitHub Desktop.
Save wmoxam/59be6be5ef1b13f6c13e9d0d21b2c622 to your computer and use it in GitHub Desktop.
> cc test.c
> ./a.out
tty_fd=3
result=0
TIOCGWINSZ=1074295912
O_EVTONLY | O_NONBLOCK=32772
147 x 46
> crystal test.cr
tty_fd=8
result=0
TIOCGWINSZ=1074295912
O_EVTONLY | O_NONBLOCK=32772
73 x 73
> crystal test.cr
tty_fd=8
result=0
TIOCGWINSZ=1074295912
O_EVTONLY | O_NONBLOCK=32772
1193 x 1193
> ./a.out
tty_fd=3
result=0
TIOCGWINSZ=1074295912
O_EVTONLY | O_NONBLOCK=32772
147 x 46
#include <stdio.h>
#include <string.h> // strerror
#include <errno.h> // errno
#include <fcntl.h> // open(), O_EVTONLY, O_NONBLOCK
#include <unistd.h> // close()
#include <sys/ioctl.h> // ioctl()
int main() {
int tty_fd = open("/dev/tty", O_EVTONLY | O_NONBLOCK);
if (tty_fd == -1) {
fprintf(stderr, "Opening `/dev/tty` failed (%d): %s\n", errno, strerror(errno));
return 1;
}
struct winsize ws;
int result = ioctl(tty_fd, TIOCGWINSZ, &ws);
close(tty_fd);
if (result == -1) {
fprintf(stderr, "Getting the size failed (%d): %s\n", errno, strerror(errno));
return 1;
}
fprintf(stdout, "tty_fd=%d\nresult=%d\nTIOCGWINSZ=%ld\nO_EVTONLY | O_NONBLOCK=%d\n%d x %d\n", tty_fd, result, TIOCGWINSZ, O_EVTONLY | O_NONBLOCK, ws.ws_col, ws.ws_row);
return 0;
}
lib LibC
TIOCGWINSZ = 0x40087468
O_EVTONLY = 0x8000
struct Winsize
ws_row : LibC::UShort
ws_col : LibC::UShort
ws_xpixel : LibC::UShort
ws_ypixel : LibC::UShort
end
fun ioctl(fd : LibC::Int, request : LibC::ULong, winsize : LibC::Winsize*) : LibC::Int
end
tty_fd = LibC.open("/dev/tty", LibC::O_EVTONLY | LibC::O_NONBLOCK)
result = LibC.ioctl(tty_fd, LibC::TIOCGWINSZ, out screen_size)
puts "tty_fd=#{tty_fd}\nresult=#{result}\nTIOCGWINSZ=#{LibC::TIOCGWINSZ}\nO_EVTONLY | O_NONBLOCK=#{LibC::O_EVTONLY | LibC::O_NONBLOCK}\n#{screen_size.ws_col} x #{screen_size.ws_col}\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment