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

I am trying to start a new perl script running using the exec command. However I want the exec command to be non-blocking so I create a new thread using the Thread module and point it toward the subroutine that will exec the new script. This new child thread also has to be non blocking so I have used the detach() command and the parent thread does not wait for the child thread. This all works fine in a console such as dos but when I run my parent script through a web browser, the child script runs fine and in a different thread but the parent script when reaching the end hangs and waits for the detached child script to end before closing the connection to the web browser. Is there any way to force the parent script to close the connection to the web browser?

Replies are listed 'Best First'.
Re: Thread and exec
by zentara (Cardinal) on Aug 18, 2005 at 12:50 UTC
    You can google for "closing stdout apache" for a bunch of discussion on how to do it, But basically the code is
    $| = 1; # need either this or to explicitly flush stdout, etc. # before forking print "Content-type: text/plain\n\n"; print "Going to start the fork now\n"; if ( !defined(my $pid = fork())) { print STDERR "fork error\n"; exit(1); } elsif ($pid == 0) { # child close(STDOUT);close(STDIN);close(STDERR); exec('./fork-long-process-test-process'); # lengthy processing } else { # parent print "forked child \$pid= $pid\n"; exit 0; }

    When I saw the node title, the first thing that poped up in my mind was a "big red warning flag" not to use exec in threads. Why? Because the exec will take over the process completely and destroy all other threads that were running under the parent, including the parent. You can "fork-and-exec" from a thread with no problem.

    The way you are describing your code, I don't see why you are even using threads to begin with? But you are seemingly on windows, and I'm clueless on how Windows does things. I mention it, because it may cause some sort of "weird" problem where you can't close STDOUT because the parent was destroyed.


    I'm not really a human, but I play one on earth. flash japh

      Windows can't fork natively. Perl emulates it using threads. See perlfork. So even if you call fork, you're really using threads behind the scenes.

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: Thread and exec
by anonymized user 468275 (Curate) on Aug 18, 2005 at 12:37 UTC
    The parent will not be free to continue until all connections (pipes, sockets, filehandles etc.) inherited by the child from the parent are closed. The child has to close those - they will typically just be STDIN and STDOUT in the context of a web application.

    One world, one people