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

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...

Replies are listed 'Best First'.
Re^4: CGI and Background Processes
by mrguy123 (Hermit) on May 05, 2008 at 15:34 UTC
    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"); ...
        Thanks, this works great!!
        I still need to apply it to my full CGI program (I tested it successfully on my dummy program) but I'm sure it will be fine
        Thanks for your help and patience (and teaching me a few new things)
        Guy