Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Starting a process in the background that lives after perl dies.

by mr_mischief (Monsignor)
on Nov 09, 2001 at 01:49 UTC ( [id://124201]=note: print w/replies, xml ) Need Help??


in reply to Starting a process in the background that lives after perl dies.

You should be able to double fork(), then dissociate the new child from the process group, then exec the other program from that grandchild.

POSIX::setsid() is your friend. POSIX is a core module, too, so its use is not subject to installation issues. Use it like this:
#!/usr/bin/perl -w use strict; use POSIX qw{setsid}; ### or just 'use POSIX;' if you plan to use other ### functions from it, of course if ( fork ) { { ### grandparent code goes here print "My grandkid should do a cute l'il ls...\n"; } exit; ### die if we're the parent } if ( fork ) { exit; ### die if we're the parent of this one, too. } ### grandchild code starts here POSIX::setsid; ### should be part of a new session now exec '/bin/ls', '.';
The above program should show a proud grandparent bragging about what its grandkid is doing. The grandchild then sticks around after the grandparent is dead. Use a loop in the grandchild if you need to prove it to yourself. The grandparent can also do whatever you want it to do, too.

Update:By all means, also close the standard file handles and chdir to the root directory as edebill suggests. I was overlooking this as assumed for serious background tasks, but I should learn sooner or later that my assumptions are not necessarily those of another monk reading my nodes.
  • Comment on Re: Starting a process in the background that lives after perl dies.
  • Download Code

Replies are listed 'Best First'.
Re: Re: Starting a process in the background that lives after perl dies.
by edebill (Scribe) on Nov 09, 2001 at 04:19 UTC
    Don't forget to close STDIN, STDOUT and STDERR, and change pwd to "/" so you don't end up with a background process keeping you from unmounting some filesystem later on. I use the following at daemon start time.
    my $pid = fork(); if($pid != 0){ exit 0; } chdir "/"; close STDOUT; close STDERR; close STDIN; POSIX::setsid(); # this takes care of controlling terminals
    Stevens covered this pretty well, I think it was "Advanced Programming in the UNIX Environment" or some such.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://124201]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (1)
As of 2024-04-15 19:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found