As c-era and broquaint say, the key is fork. This will
make a "clone" of your program that is not attached to the terminal, and thus, the main program can exit and leave you with the shell prompt.
This is all fine and well, but make sure you are aware of some key issues:
- Don't fork right away. Make sure your program is "up and running" before the big fork call. This way you can report any errors, such as those with command line parameters or configuration files, to the console. If you fork and then warn or die, the output can't be captured. If this is called from a "crontab", you won't even see the error. So, configure, warn/die if required, then fork.
- Sometimes you don't want the program to fork. Including an option that prevents this, or alternatively, enables this, would be helpful when trying to debug. Otherwise your debugger might stop on the fork call, leaving your clone to run wild and free.
- If your program is a "daemon" type process, try and blend in by following standard conventions. This might mean making an "/etc/rc.d/"-compatible (SysV-Init) RC boot file, creating a PID file in /var/run, and so forth. This will help you figure out if your thing is running already, and help manage start/stop operations.
Just food for thought. | [reply] |
my $pid = fork;
exit if ($pid);
# Your code here
| [reply] [d/l] |
You can't unfortunately, but this is a 'limit' of OSes, and not of perl. So you probably either want to take advantage of multi-tasking in *nix-type shells or fork() off at the beginning of your program.
prompt> perl source.pl &
or with perl
use strict;
fork() and exit(0);
print "Now in the child process\n";
The perl example is a little hackish, but there's plenty of documentation about to explain it all.
HTH
broquaint | [reply] [d/l] [select] |
For Windows platforms you might also want to look at Win32::Process
--Jim | [reply] |
use POSIX;
sub daemon {
if($pid = fork) {
# Parent
exit 0;
} elsif (defined $pid) {
# Child
setsid(); # detach session
do_stuff(); # do some usefull stuff
} else {
die "Cannot fork: $!\n";
}
}
| [reply] [d/l] |
| [reply] |
If you want your process to properly act as a daemon, then the simplest
method is to use the Proc::Daemon module:
#!/usr/bin/perl -w
use strict;
use Proc::Daemon;
Proc::Daemon::Init;
# your code goes here
__END__
This module takes care of all the little things necessary for proper
daemonization: as per the docs:
- Forks a child and exits the parent process.
- Becomes a session leader (which detaches the program
from the controlling terminal).
- Forks another child process and exits first child.
This prevents the potential of acquiring a controlling
terminal.
- Changes the current working directory to "/".
- Clears the file creation mask.
- Closes all open file descriptors.
| [reply] [d/l] |
I just asked a very similar question the other day. You
can find a long discussion here.
| [reply] |