Work:Using FastCGI with Perl
Contents |
Developing FastCGI Applications in Perl
FastCGI is ideal for applications written in Perl, because it provides a huge performance gain. When you run a Perl script, the Perl interpreter analyzes the entire script before executing any of it. With FastCGI, you can factor out this initialization cost and pay it only once, making execution of the actual script much faster in response to client calls.
Getting Started
The first line of any Perl script typically specifies the pathname of the Perl interpreter itself.
Next, you must tell Perl to load the FastCGI extension. To do so, place the following line near the beginning of every FastCGI script:
use FCGI;
Then, you have to divide FastCGI scripts into the following two sections:
* Initialization section, which is executed only once. * Response loop section, which gets executed every time the FastCGI script gets called.
A response loop typically has the following format:
while (FCGI::accept >= 0) {
# body of response loop
}
The accept call returns 0 whenever a client requests the FastCGI script. Otherwise, the accept call returns -1.
Example: Hello.pl
Here is a simple example of a FastCGI application written in Perl:
#!/usr/bin/perl -w use strict; use warnings; use FCGI; # Imports the library; required line # Initialization code my $cnt = 0; # Response loop while (FCGI::accept >= 0) { print "Content-type: text/html\r\n\r\n"; print "<head>\n<title>FastCGI Hello World</title>\n</head>\n"; print "<h1>FastCGI Hello World</h1>\n"; print "This is coming from a FastCGI server.\n<BR>\n"; print "Running on <EM>$ENV{SERVER_NAME}</EM> to <EM>$ENV{REMOTE_HOST}</EM>\n<BR>\n"; $cnt++; print "This is connection number $cnt\n"; }
.htaccess
Now you'll need to create or modify your .htaccess in the same directory you are running the script and add the following lines to it:
Options +ExecCGI AddHandler fcgid-script .pl
substitute .pl with what ever extension you use for your cgi scripts. (//Example .fcgi or .cgi//)
More Info
Visit http://search.cpan.org/~skimo/FCGI-0.67/FCGI.PL FCGI on CPAN for more methods to build more in depth FastCGI scripts in Perl.