in reply to Re: CGI and Background Processes
in thread CGI and Background Processes

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.

Replies are listed 'Best First'.
Re^3: CGI and Background Processes
by almut (Canon) on May 05, 2008 at 15:04 UTC
    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?

        You need to reopen them to somewhere, e.g. something like

        ... 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"); ...