Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Answer: How do I run a script in the background? How should I run a script as daemon?

( #42001=categorized answer: print w/ replies, xml ) Need Help??

Q&A > input and output > How do I run a script in the background? How should I run a script as daemon? contributed by jeroenes

If you run a script in a the background with exec, things go nasty after a while when you kill your terminal. You can prevent this (I tried it only under linux) by setting SIG{INT}='IGNORE'.

Actually, a better solution is the Proc::daemon module, or the Net::daemon module if you need to claim a socket.

Comment on Answer: How do I run a script in the background? How should I run a script as daemon?
Select or Download Code
Re: Answer: How do I run a script in the background? How should I run a script as daemon?
by Fastolfe (Vicar) on Nov 17, 2000 at 00:54 UTC
    If you disassociate the process from its parent (via setsid), this won't happen. When you kill your terminal (or exit it any way other than by typing "exit" or "logout"), a HUP signal is sent to the terminal's process group. This means every process that currently is in the shell's process group receives the HUP signal, which effectively kills everything started during that shell session.

    The approved way of disassociating a process from its process group is by changing its process group ID (pgid), such as via setsid. See perlipc and my other comment at Answer: Is it possible to background a perl script from within itself? for a method to cleanly do this.

      Why yes, you're right, but our friend, the late W. Richard Stevens goes farther and explains that the best method is as following:
      #untested code conversion from C sources exit if fork()!=0; setsid(); $SIG{'HUP'}='IGNORE'; exit if fork()!=0; chdir('/'); #prevents path-specific hax umask(0); #clear file mode creation mask openlog(...); #standard syslog call
      With the second call to fork, we are guaranteed that the child is not a session leader and therefore cannot acquire a controlling terminal. We ignore SIGHUP since the session leader is soon to be terminated. Just an expansion on what you said. I certainly admire and trust the late Mr. Stevens very much!
      AgentM Systems nor Nasca Enterprises nor Bone::Easy nor Macperl is responsible for the comments made by AgentM. Remember, you can build any logical system with NOR.
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2014-12-27 10:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls