I have a piece of one of my mod_perl apps that potentially takes quite a
while to complete. What I would like to do is to get Apache/mod_perl to
start a second process which would do the work, return a page to the
user, and get on with the next thing..
I just did the following yesterday (for generating some PDFs and email them to the user after finishing). So far it seems to work for me (Slackware 9, Apache 2.0.48, mod_perl 1.99.11, Perl 5.8.0). It's adopted from:
http://perl.apache.org/docs/1.0/guide/performance.html#Forking_and_Executing_Subprocesses_from_mod_perl
regards, Christian
-------------------------------------------------- #!/usr/bin/perl -w
use strict; use POSIX 'setsid';
# parent code goes here
$SIG{CHLD} = 'IGNORE'; defined (my $kid = fork) or die "Cannot fork: $!\n"; if ($kid) { print "Parent $$ has finished, kid's PID: $kid\n"; } else { chdir '/' or die "Can't chdir to /: $!"; open STDIN, '/dev/null' or die "Can't read /dev/null: $!"; open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!"; # comment this out, if you want to keep apache error log, works for me open STDERR, '>/tmp/log' or die "Can't write to /tmp/log: $!"; setsid or die "Can't start a new session: $!";
my $oldfh = select STDERR; local $| = 1; select $oldfh; warn "started background task foo from $0\n"; # do something time-consuming sleep 1, warn "$_\n" for 1..20; warn "finished background task foo from $0\n";
CORE::exit(0); # terminate the process }
# other parent code
-- Reporting bugs: http://perl.apache.org/bugs/ Mail list info: http://perl.apache.org/maillist/modperl.html