[Chicago-talk] capturing the pts/?

Andrew Rodland andrew at cleverdomain.org
Sun Feb 28 17:01:01 PST 2010


On Sunday 28 February 2010 06:16:43 pm Richard Reina wrote:
> Does anyone know if there is a perl function that in linux captures the
> terminal number (pts/0, pts/1, pts/3, etc.) that the script is being run
> in?

POSIX::ttyname. Call it as ttyname(0), or if you want to be a bit more 
persistent, do:

sub get_tty {
  for (0 .. 2) {
    if (my $ttyname = POSIX::ttyname($_)) {
      return $ttyname;
    }
  }
  return;
}

which works as long as one of stdin, stdout, or stderr is connected to a 
terminal (often, like when running in a pipeline, stdin and stdout will both 
be opened to a pipe or a file, but stdout will still be pointing to the 
terminal, so this is a good trick.)

Andrew


More information about the Chicago-talk mailing list