http://qs321.pair.com?node_id=321042

hotshot has asked for the wisdom of the Perl Monks concerning the following question:

Hello all!

I have a cgi script that calls an external script to run on background, for example:
`$myScript &`;
The problem is that the apache probably waits on this script and returns only after the script ends (I wrote such a script that only sleeps for 30 sec and the web page returned to me after 30 sec and not immediatelly as expected).

when I run a regular perl scripts that calls $myScript in the background, I have no problem, the prompt returns immediatelly and the script runs in the background.
Anyone has an idea what's the problem here and how to solve it?

Thanks

Replies are listed 'Best First'.
Re: http waits on process
by waswas-fng (Curate) on Jan 13, 2004 at 18:14 UTC
    Back ticks ` are used in perl to execute and use the output -- so perl is waiting for the output of the command even though it is in the background. I hate to beat merlyn to the punch but he has an article about this. =)


    -Waswas
Re: http waits on process
by etcshadow (Priest) on Jan 13, 2004 at 20:57 UTC
    The problem is that when you call
    `$myscript &`;
    You are essentially calling
    `sh -c '$myscript &'`;
    In other words... you are waiting for the shell process to terminate... but the shell process (if it were interactive) would have returned a prompt imediately after firing off $myScript.

    If you really want to fire off a background job from a perl process, and don't care about the output (btw: backticks imply that you do care about the output, but continuing imediately imply that you do not care about the output)... then you should do something more like this:

    my $pid = fork; die "Could not fork: $!" unless defined $pid; if (!$pid) { exec $myScript; }
    Which is somewhat akin to what the shell does when you launch the program foo by typing:
    [user@host]$ foo &
    ------------ :Wq Not an editor command: Wq
      As I said, the problem happened only when I did it from cgi script through the web page, when I tried it from a regular script, I had no problem.
      Additionally, I already tried the solution you suggested (fork and exec), and still I get the same problem, I think it something related to apache that waits for stdout or someting (closing stdout, didn't work also).
      Do you have another idea?