15.2. Testing Whether a Program Is Running InteractivelyProblemYou want to know whether your program is being called interactively or not. For instance, a user running your program from a shell is interactive, whereas the program being called from cron is not. Solution
Use sub I_am_interactive { return -t STDIN && -t STDOUT; } If you're on a POSIX system, test process groups: use POSIX qw/getpgrp tcgetpgrp/; sub I_am_interactive { local *TTY; # local file handle open(TTY, "/dev/tty") or die "can't open /dev/tty: $!"; my $tpgrp = tcgetpgrp(fileno(TTY)); my $pgrp = getpgrp(); close TTY; return ($tpgrp == $pgrp); } Discussion
The
-t
operator tells whether the filehandle or file is a
tty device. Such devices are signs of interactive use. This only tells you whether your program has been redirected. Running your program from the shell and redirecting STDIN and STDOUT makes the
-t
version of
The POSIX test tells you whether your program has exclusive control over its tty. A program whose input and output has been redirected still can control its tty if it wants to, so the POSIX version of
Whichever while (1) { if (I_am_interactive()) { print "Prompt: "; } $line = <STDIN>; last unless defined $line; # do something with the line } Or, more clearly: sub prompt { print "Prompt: " if I_am_interactive() } for (prompt(); $line = <STDIN>; prompt()) { # do something with the line } See AlsoThe documentation for the standard POSIX module, also in Chapter 7 of Programming Perl ; the -t file-test operator in Chapter 3 of Programming Perl and in perlop (1) |
|