4

There are any number of tutorials out there on how to use FastCGI to CGI wrappers to serve Perl code using nginx. But I'm comfortable working with Perl modules myself, so I don't need the wrapper. I'm trying to figure out the right way to set this up. Here's the code I have so far:

#!perl

use CGI;
use FCGI;

my $s = FCGI::OpenSocket(':9000',20);
my $r = FCGI::Request( \*STDIN, \*STDOUT, \*STDERR,
    \%ENV, $s);
while ($r->Accept >= 0) {
    my $cgi = CGI->new;
    print "Content-type: text/html\n\n";
    print "<html><body>The foo input is ", $cgi->param('foo'), "</body></html>";
    $r->Finish;
}

And enable it in nginx like so:

location /foo {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.pl;
}

The problem is that no matter how many times I call the script, param returns the same value that was passed the very first time it was called since starting the program. Is there a better way of doing this? I'm open to alternatives to CGI.pm as well.

2
  • Your posted code would have worked fine if you have instructed CGI.pm to clear it's global cache before you instantiated CGI.pm. CGI::initialize_globals(); Commented Sep 3, 2011 at 13:39
  • Interesting. Didn't know about that one. I'll keep it in mind. Commented Sep 3, 2011 at 14:45

1 Answer 1

1

CGI::Fast will handle most of the work for you, including setting up the daemon.

use CGI::Fast;

local $ENV{FCGI_SOCKET_PATH} = ":9000";
local $ENV{FCGI_LISTEN_QUEUE} = 20;

while ($q = CGI::Fast->new) {
    print $q->header;
    print "<html><body>The foo input is ", $cgi->param('foo'), "</body></html>";
}

An alternative is Nginx::Simple which gives you more control over the behavior of your cgi-script-as-daemon.

Sign up to request clarification or add additional context in comments.

2 Comments

Having some trouble with CGI::Fast. I tried running it on the command line, and it simply ran once and exited. So it doesn't seem to have listened to the port, or bound the stdio streams etc.
Got it working in the end, but there seems to be a documentation bug in CGI::Fast regarding environment variables, which I can report.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.