Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
IO#ttyname
io.ttyname → string or nil
ext/io/console/console.c
View on GitHub ↗
static VALUE
console_ttyname(VALUE io)
{
int fd = rb_io_descriptor(io);
if (!isatty(fd)) return Qnil;
# if defined _WIN32
return rb_usascii_str_new_lit("con");
# elif defined HAVE_TTYNAME_R
{
# ifdef TTYNAME_R_RETURNS_CHAR_P
# define ttyname_r(fd, name, size) (ttyname_r(fd, name, size) == NULL ? errno : 0)
# endif
char termname[1024], *tn = termname;
size_t size = sizeof(termname);
int e;
if ((e = ttyname_r(fd, tn, size)) == 0)
return rb_interned_str_cstr(tn);
if (e == ERANGE) {
VALUE s = rb_str_new(0, size);
while (1) {
tn = RSTRING_PTR(s);
size = rb_str_capacity(s);
if ((e = ttyname_r(fd, tn, size)) == 0) {
return rb_str_to_interned_str(rb_str_resize(s, strlen(tn)));
}
if (e != ERANGE) break;
if ((size *= 2) >= INT_MAX/2) break;
rb_str_resize(s, size);
}
}
rb_syserr_fail_str(e, rb_sprintf("ttyname_r(%d)", fd));
UNREACHABLE_RETURN(Qnil);
}
# elif defined HAVE_TTYNAME
{
const char *tn = ttyname(fd);
if (!tn) {
int e = errno;
rb_syserr_fail_str(e, rb_sprintf("ttyname(%d)", fd));
}
return rb_interned_str_cstr(tn);
}
# else
# error No ttyname function
# endif
}
Returns name of associated terminal (tty) if io is a tty. Returns nil otherwise.