Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a Perl script is running in a terminal?

Tags:

linux

perl

tty

I'm trying to determine, within a Perl script on Linux, whether it's running in a terminal.

That is, I need code that:

  • returns true when simply running on the command-line
  • also returns true when running ./myscript.pl | less or even ./myscript.pl </dev/null >/dev/null 2>/dev/null
  • returns false when running in a cron job, or as a CGI script

Especially because of the second bullet, I can't use -t STDOUT and variations, and also IO::Interactive is of no use.

The information does appear to be available. If I run ps, it shows an entry like pts/2 in the TTY column, even when I run ./myscript.pl </dev/null >/dev/null 2>/dev/null, and ? when running as a cron job or CGI script.

Is there an elegant way to determine this in a Perl script? I'd rather not have to parse the output of ps.

like image 731
mscha Avatar asked Aug 05 '11 10:08

mscha


1 Answers

You can try to open /dev/tty. This will work if you are in a terminal (even in a terminal on a remote computer). Otherwise, if the script is run via at or cron, it won't.

Note: this will only work on Unix systems.

like image 117
Ingo Avatar answered Sep 27 '22 20:09

Ingo