How to check if Perl script is working in terminal?

I am trying to define inside a Perl script on Linux, regardless of whether it works in the terminal.

That is, I need a code that:

  • returns true on simple command line startup
  • also returns true on startup ./myscript.pl | less ./myscript.pl | less or even ./myscript.pl </dev/null >/dev/null 2>/dev/null
  • returns false when run in cron job or as a cgi script

Especially because of the second bullet, I can't use -t STDOUT and options, as well as IO :: Interactive is useless.

Information appears to be available. If I started ps , an entry like pts/2 will appear in the TTY column, even when I run ./myscript.pl </dev/null >/dev/null 2>/dev/null and ? when working as a cron job or CGI script.

Is there an elegant way to define this in a Perl script? I would prefer not to parse the ps output.

+6
source share
4 answers

You can try opening / 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 through or cron, it will not.

Note: this will only work on Unix systems.

+10
source

Another answer to my question. I examined the ps source to find out how it defined TTY, and uses /proc/[pid]/stat .

 use strict; use warnings; use 5.010; use autodie; sub isatty() { # See http://www.kernel.org/doc/man-pages/online/pages/man5/proc.5.html open(my $stat, '<', "/proc/$$/stat"); if (<$stat> =~ m{^\d+\s+\(.*\)\s+\w\s+\d+\s+\d+\s+\d+\s+(\d+)}) { return $1 > 0; } else { die "Unexpected format in /proc/$$/stat"; } } 
+4
source

PS should help you.
ps aux | grep 'filename.pl'

+1
source

To partially answer my own question, the following trick:

 sub isatty() { my $tty = `/bin/ps -p $$ -o tty --no-headers`; $tty =~ s{[\s?]}{}g; return $tty; } 

Returns the name TTY if it is (true), or "" if not (false).

I would prefer a solution without an external team ...

0
source

Source: https://habr.com/ru/post/894372/


All Articles