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

I need a really simple perl script that runs certain program (that never returns, a background process) and ends immediately after that.

My problem is that the perl script never really ends. I've tried threads, fork, and whatnot, but there is always some zombie or defunct process, or just keeps running in 'ps'.

Normally this shouldn't be a problem... I can afford a little stray process every now and then... But this script needs to be executed via cgi, and if it doesn't end "gracefully", the server never sends the reply to the client.

This is the best I've done so far (without warnings and ignoring errors, just the main stuff):

#!/usr/bin/perl $SIG{CHLD} = 'IGNORE'; open STDIN, '/dev/null/'; open STDOUT, '>/dev/null/'; open STDERR, '>/dev/null/'; exit if fork(); chdir '../working/dir'; system './program &';

Any advice is greatle appreciated.

Replies are listed 'Best First'.
Re: run a background process
by merlyn (Sage) on Jul 14, 2005 at 11:04 UTC
      Thank you! I forgot completely about close *bonk self*

      This worked:

      exit if fork(); close STDOUT; close STDERR; chdir './somewhere'; exec './somestuff';
Re: run a background process
by blazar (Canon) on Jul 14, 2005 at 10:02 UTC
    Since you fork in the first place, why not exec as well, rather than system?!?
      tried that already.

      It seems to work well when running from the terminal, but if run from cgi, there's still no response, and 'ps x' shows a zombie process:
      [script.pl] <defunct>

        Then smell of XY here: (nearly) no experience with cgi myself, but do you really want your cgi process to fork a background running task and then exit?

        Maybe giving a peek into perlipc may give you some ideas about other ways to accomplish what you're really after...

Re: run a background process
by anonymized user 468275 (Curate) on Jul 14, 2005 at 12:05 UTC
    Using Solaris I just tried a simple:

    perl -e 'system "sleep 5000 \&";'
    and the perl script exited leaving the child alive. The same was true when putting the code into a script file. Can you say what your platform is?

    One world, one people