in reply to CGI and Background Processes

In my experience (at least with Apache) you need to close STDERR in addition to STDOUT, because Apache (or mod_cgi to be more precise) sets up two pipes to the CGI program (STDERR is connected to Apache's error log), which get duplicated when the CGI process forks... If you don't close them before starting the long-running process, Apache will wait for those handles to be closed by that forked process before it finishes the request cycle.

Preferably start the long-running process via fork/exec, in which case you can conveniently close STDOUT/STDERR after the fork (so the handles remain functional in the main CGI), but before doing the exec.

(A similar question came up recently, btw.)

Replies are listed 'Best First'.
Re^2: CGI and Background Processes
by mrguy123 (Hermit) on May 05, 2008 at 14:43 UTC
    Thanks, it worked
    I still have to decide if this is the way to go, but at least I know that there's a solution
    UPDATE:
    This seems to work. Unfortunately the background process is supposed to print out to a log. Because STDOUT and STDERR are closed, there is no log.
    It seems that I need to think of another option.
      the background process is supposed to print out to a log

      just reopen STDOUT/STDERR to wherever you want to log to (one of them, or both), instead of closing them...

        This doesn't seem to be working for me. This is the code I have now:
        #!/usr/bin/perl use strict; use warnings; print "Content-type: text/html\n\n"; print <<END_OF_PAGE; <HTML> <HEAD> <TITLE>Waiting</TITLE> </HEAD> <BODY> <P> Waiting Some more </P> </BODY> </HTML> END_OF_PAGE reopen STDOUT; reopen STDERR; system "perl sleep.pl > out ";
        The sleeping program is (text book style):
        use strict; use warnings; print "going to sleep\n"; my $i = 0; while ($i<20){ sleep (1); print "zzz\n"; $i++; } print "finished my beauty sleep\n";
        I've also tried to close and the reopen the output streams. I still can't seem to get anything to go to the log file.
        I'm not sure how to use fork() for another process but I can look it up. The question is whether it will fix this problem.
        Any ideas?