Am Samstag, 5. März 2005 19.48 schrieb Peter Rabbitson:
> How would I implement a simple detection mechanism, to be able to run the
> same script from he commnd line and from cgi, having the script behave
> differently depending on the invocation? (e.g. change the content type and
> other formatting stuff)

A) (not really what you want)

sub interactive {
 return -t STDIN && -t STDOUT
}

The file test operator -t tells you if the filehandle is a tty or not.
But, if you use it in a program whose STDIN/STDOUT are redirected, even if 
called from cmdline, the sub returns false. Called by cron, it returns also 
false.


B) Maybe what you want, if you use a POSIX compliant system
    (there may be better solutions or even a module):

# has the prog control over its tty? 
# returns true even if STDIN/STDOUT are redirected;
# returns false if called by cron
# (see man POSIX)
# [tested]
#
use POSIX qw/getpgrp tcgetpgrp/;
sub controls_tty {
 local *TTY;
 open TTY, "/dev/tty" or die "error opening tty: $!";
 my $tpgrp=tcgetpgrp(fileno(TTY));
 my $pgrp =getpgrp();
 close TTY or warn "error closing tty: $!";
 return ($tpgrp==$pgrp);
}

# returns true if run under CGI
# since the server defines GATEWAY_INTERFACE
# [untested]
#
sub from_cgi {
 return $ENV{GATEWAY_INTERFACE}=~/^CGI/o ? 1 : 0;
}

# check between three cases:
# [untested]
#
if (from_cgi()) {
 print "called by CGI";
}
elsif (controls_tty) {
 print "called from cli";
}
else {
 print "called from cron (e.g.?)";
}


corrections from others are welcome :-)

greetings joe

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to