Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

detacher.pl

by enemyofthestate (Monk)
on Apr 29, 2005 at 05:02 UTC ( [id://452523]=sourcecode: print w/replies, xml ) Need Help??
Category: utility scripts
Author/Contact Info StephenCarville stephen@totalflood.com
Description: Detaches itself from the terminal and starts a program. Orgianally written to start java code that refused to go into the background. Since then I've used it on perl 'daemons' as well. Based in a trick I learned way back in my OS-9 days.
#!/usr/bin/perl -w

# detach from the terminal, go into the BG and then exec a program
# detacher.pl <program> {parm1} {parm2} ...

use strict;

sub main {

  my ($pid,$line);
  my (@args);

  # fork and exit if parent
  $pid = fork;
  if($pid) { exit 0; }

  # duplicate STD paths
  open (DUPOUT,">&STDOUT");
  open (DUPERR,">&STDERR");
  open (DUPIN, "<&STDIN");

  # close STD paths so parent can exit clenaly
  close STDOUT;
  close STDERR;
  close STDIN;

  # restore the STD paths from duplicates
  open (STDOUT,">&DUPOUT");
  open (STDERR,">&DUPERR");
  open (STDIN,"<&DUPIN");

  # avoid leaks! close teh duplicate paths
  close DUPOUT;
  close DUPERR;
  close DUPIN;

  # construct a command list
  @args = ();
  foreach $line (@ARGV) {
    push @args,$line;
  }

  # finally exec the new program
  exec @args;
}

main()
Replies are listed 'Best First'.
Re: detacher.pl
by Tanktalus (Canon) on Apr 29, 2005 at 13:56 UTC

    Slightly simpler is to use Proc::Daemon.

    use Proc::Daemon; Proc::Daemon::Init; exec @ARGV;
    Or ...
    perl -MProc::Daemon -e 'Proc::Daemon::Init; exec @ARGV' some command h +ere
    The difference is that this will start a new session, making it pretty much impossible that the background process will gain access to any terminal.

    I'm sure someone could golf this down further, but I'm just trying to get simpler, not smaller. :-)

      Thanks. I'll take a look at that.

      Simple is good...

Re: detacher.pl
by naChoZ (Curate) on May 01, 2005 at 01:47 UTC

    I've used Proc::Daemon with good results myself. But if you want to run something in the background and still be able to reattach to it and use it, use the screen utility. It's readily available for lots of operating systems.

    --
    naChoZ

    Where in the nursery rhyme does it say Humpty Dumpty is an egg?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2024-03-19 04:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found