Ravi
Ravi

Reputation: 1710

fork with CGI::Fast perl

I'm using fork with CGI::Fast in perl.
When I run it normally, it prints In handle request 5 times as expected.
But when I configure this file as a fast cgi in apache server, It prints In handle request only one time.
Can anybody help me out here.

Sample program:

#!/usr/bin/perl

use strict;
use warnings;
use CGI::Fast;
use Data::Dumper;
use HTML::Template;

while(my $query = CGI::Fast->new()) {
    my $timeout ='60';

    eval {
        local $SIG{ALRM} = sub  {
            print STDERR "Fcgi error";
            exit(0);
        };

        alarm $timeout;
        #wait till all the result returns
        my $val = process_request( $query );
        alarm 0;
    } or print STDERR $@;
}

sub process_request{
    my $query = shift;
    my @childs = ();
    print $query->header;

    foreach my $i ( 1..5 ) {
        my $pid = fork();
        if( $pid ) {
            push( @childs, $pid );
        }
        elsif( $pid == 0 ) {
            _handle_request();
            exit(0);
        }
    }
    foreach my $child ( @childs ) {
        my $pid = waitpid( $child, 0 );
    }

    return;
}

sub _handle_request{
    print "In handle request<br/>";
    return;
}

Upvotes: 1

Views: 429

Answers (1)

Dave Sherohman
Dave Sherohman

Reputation: 46187

The FastCGI FAQ includes a section specifically on How do I use fork or exec? in Perl.

When you fork, however, without calling exec as well, i.e. when you have two instance of perl running, the request handle object will (eventually) be destroyed in both instances of perl. As a result, a possible request being handled will be finished when the object is destroyed for the first time. This is probably not what you expect, since you will usually only be handling the request in either the parent or the child. To inhibit this unwanted request finishing, you can send the Detach() message to the request handle object. In a detached state, destruction will not lead to any finishing of requests. It is advised you call Detach() before forking and Attach afterwards (in the process that will continue handling the request).

What's probably happening is that, after the first forked child sends its response, it marks the request as complete and the connection to the client is closed before the other children send their responses.

Upvotes: 1

Related Questions