... sub background_run { my @cmd = @_; if (my $pid = fork) { # parent # (...) } elsif (defined $pid) { # child # This redirects both STDOUT/STDERR to the same logfile. # Instead of appending (">>"), you could of course also # create the file anew every time (">"), or create two # separate logfiles, or whatever... my $logfile = "/tmp/bgrun.log"; # re-open STDERR/STDOUT (closes first implicitly) # (if this fails, the error msg will end up in Apache's error_log) open STDERR, ">>", $logfile or die "Couldn't open $logfile: $!"; open STDOUT, ">>", $logfile or die "Couldn't open $logfile: $!"; # optional # my $app_path = "/path/to/dir/to/run/long-running-cgi/in"; # chdir $app_path or die "Couldn't chdir() to $app_path: $!"; exec @cmd; die "Couldn't exec '@cmd': $!"; } else { die "Couldn't fork: $!"; } } ... # files (perl, sleep.pl) must be found - in case of doubt, # use absolute paths... background_run("perl", "./sleep.pl"); ...