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

I am trying to use fork to run a process in the background while the parent process continues running its own code. What I have is:

Neils Program:

#!/usr/local/bin/perl # some code if ($pid = fork ) { print "this is the parent\n"; } else { print "this is the child\n"; exec `some unix command that does not terminate`; } # more of Neils code exit;

It is my goal to run neil's program, kick off the unix command in background mode then continue running more of Neil's code. When I run this program and do a ps -ef on my solaris 9 machine I get:

What I want to happen is if I do a ps -ef, then I should get one copy of Neil's main program and one copy of Neil's child process. Furthermore, if I kill Neil's Main program, the child should die. I have tried the examples of fork in the Perl Cookbook with similar results.

Finally, the reason that I do not use a pipe to an open statement is that using this process prevents my child process from communicating to its license server. So I am trying a different approach using fork.

thanks for any suggestions

W3NTP
neil

Replies are listed 'Best First'.
Re: how to run a process in background mode
by flyingmoose (Priest) on Mar 24, 2004 at 22:05 UTC
    A very nice module that makes this simple on Windows and Linux, as well as allowing you to either ignore or wait on a process, is Proc::Background. Use this if you can, and only worry about fork and exec if you need to run arbitrary code in those places. If you are doing system calls, Proc::Background is for you.
      This is exactly the program that I am looking for. Loaded it and it works just like I need it to. Many many thanks W3NTP (Neil)
Re: how to run a process in background mode
by halley (Prior) on Mar 24, 2004 at 21:12 UTC
    Is that a typo? Replace
    exec `some unix command`;
    with
    exec 'some unix command';
    You probably don't want to exec a command line that was printed by some other command. The backticks (see perldoc perlop about qx) collect output from a command, while exec takes a string argument.

    --
    [ e d @ h a l l e y . c c ]

Re: how to run a process in background mode
by Vautrin (Hermit) on Mar 24, 2004 at 20:53 UTC
    Why don't you just use system("command &"); to background the command that you are running and then have the fork exit (0);? (Remember to install a signal handler for CHLD. Also, check whether or not your fork is defined. If it isn't, die -- you've run out of system resources and are probably fork bombing your box).

    Want to support the EFF and FSF by buying cool stuff? Click here.
      Thanks for the response. Tried this and it did not do what I needed it to do. Got proc::Background. was the exact solution for my application thanks for the response and assist W3NTP