Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fork properly with mod_perl2?

Tags:

perl

mod-perl2

I'm having trouble forking a long-running process from some code running under mod_perl2.

Everything works for the most part, but it seems that the forked process is holding open handles to Apache's logfiles - this means Apache won't restart while the process is running (I get a 'failed to open logfiles' message).

Here's the code I'm using:

use POSIX; # required for setsid

# Do not wait for child processes to complete
$SIG{CHLD} = 'IGNORE';

# fork (and make sure we did!)
defined (my $kid = fork) or die "Cannot fork: $!\n";

if ($kid) {
    return (1, $kid);
}else {
    # chdir to /, stops the process from preventing an unmount
    chdir '/' or die "Can't chdir to /: $!";

    # dump our STDIN and STDOUT handles
    open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
    open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";

    # redirect for logging
    open STDERR, '>', $log_filename or die "Can't write to log: $!";

    # Prevent locking to apache process
    setsid or die "Can't start a new session: $!";

    # execute the command
    exec( $cmd, @args );

    die "Failed to exec";
}

Back in the mod_perl1 days, I recall using $r->cleanup_for_exec to solve this problem, but it doesn't seem to be supported under mod_perl2. (Edit: Apparently it's not required any more..)

Any advice on how to correctly start a long-running process from mod_perl2 without these problems would be greatly appreciated!

like image 200
Dan Avatar asked Jan 23 '09 02:01

Dan


2 Answers

You probably want to read this discussion. It seems you shouldn't fork on mod_perl unless you know how to prepare things. You have to use a module such as Apache2::SubProcess

like image 151
Leon Timmermans Avatar answered Nov 08 '22 00:11

Leon Timmermans


Try closing your STDIN/STDOUT handles before the fork.

like image 43
nezroy Avatar answered Nov 08 '22 02:11

nezroy