简体   繁体   English

Perl如何检测是从命令行运行还是从浏览器调用

[英]Perl how to detect if running from the command line or called from browser

Is there a good way to detect if the Perl script is called from terminal/DOS or called from a web server. 有没有一种好的方法来检测Perl脚本是从终端/ DOS调用还是从Web服务器调用。

I currently have this code: 我目前有以下代码:

sub cli {
    # return 1 if called from browser, 0 if called from command line
    if  (defined $ENV{GATEWAY_INTERFACE} ||  exists $ENV{HTTP_HOST}){
        return 0;
    }
    return 1;
}

but read that these ENV variables are not set by all servers. 但请注意,并非所有服务器都设置了这些ENV变量。

The reason for this if the script run from terminal I will print text/plain formatted messages, if run from browser I will print HTML formatted messages. 这样做的原因是,如果脚本是从终端运行的,我将打印文本/纯格式的消息,如果是从浏览器运行的,则我将打印HTML格式的消息。

I usually do: 我通常这样做:

if (-t STDIN) {
    //This is running from a terminal
}

Edit after reading comments : I found this other question that details a different solution : How do I check if a Perl script is running in a terminal? 阅读评论后进行编辑 :我发现了另一个问题,该问题详述了另一个解决方案: 如何检查Perl脚本是否在终端中运行? .

The following is a quick example and may not be the most accurate, but serves to demonstrate that you could check the process's parent command. 以下是一个简单的示例,它可能不是最准确的示例,但可以证明您可以检查流程的父命令。

my $parent_process  = `ps -o ppid= -p $$ | xargs ps -o command= -p`;
if ($parent_process =~ /httpd/) {
   say q{CGI};
} else {
   say q{Terminal};
}

Basically, we retrieve the search for the current process, and pipe that parent process into another look up so that we can get the parent's command that was run. 基本上,我们检索对当前进程的搜索,并将该父进程通过管道传输到另一个查找中,以便我们可以获取已运行的父进程的命令。 From the terminal it should be the shell name (eg, -bash ), but if it was run by the server, it should be the server daemon httpd (depending on the web server). 在终端上,它应该是shell名称(例如, -bash ),但是如果它是由服务器运行的,则应该是服务器守护程序httpd (取决于Web服务器)。

It would be much easier to have the server set an environment variable and check for the existence of that variable. 让服务器设置环境变量并检查该变量的存在会容易得多。 This all depends on where you're running the command and who you're running the command as. 这完全取决于您在何处运行命令以及在何处运行命令。

This could further be condensed into something like: 这可以进一步浓缩为:

my $is_server = `ps -o ppid= -p $$ | xargs ps -o command= -p | grep httpd -q && echo "1" || echo "0"`; chomp $is_server;
if ($is_server) { ... } else { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM