Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Daemonize a Ruby process

// description of your code here
from : http://scie.nti.st/2006/12/15/daemonize-a-ruby-process
Here's a neat thing I found. I needed a small bit of Ruby code to run continuously in the background, but because of how Capistrano can't seem to work well with "nohup" and "&" (background job), my ruby script itself needed to be able to fork and detach from the terminal. Here's how you do it:
#!/usr/bin/ruby

pid = fork do
  Signal.trap('HUP', 'IGNORE') # Don't die upon logout

  loop do

    // Some code

    sleep 60
  end
end

Process.detach(pid)

PyS60 - DaemonS60

// description of your code here

import appuifw
import e32
import thread

lock = e32.Ao_lock()
lockTHR = thread.allocate_lock()

###### Sostituisci questa funzione con quello che vuoi fare eseguire
i = 0
def funzDaemon():
	global i
	while(1):
		lockTHR.acquire()
		e32.ao_sleep(1)
		open('E:\\Others\\tmp.txt', 'a').write(str(i)+"\n")
		i+=1
		lockTHR.release()
####################################################################

appuifw.app.title = u'DaemonS60'
appuifw.app.exit_key_handler = lambda:lock.signal()

print 'DaemonS60 - Start'

thread.start_new_thread(funzDaemon, ())

lock.wait()

print 'DaemonS60 - Stop'

Linux - Example Crontab

// Esegue lo script ogni ora

// Minute(0-59) Hours(0-23) DayOfMonth(1-31) Month(1-12) DayOfWeek(0-6/Sun-Sat) Command
* */1 * * * script.sh

Daemonize a Ruby process

Here's a neat thing I found. I needed a small bit of Ruby code to run continuously in the background, but because of how Capistrano can't seem to work well with "nohup" and "&" (background job), my ruby script itself needed to be able to fork and detach from the terminal. Here's how you do it:

#!/usr/bin/ruby

pid = fork do
  loop do

    // Some code

    sleep 1.minute
  end
end

Process.detach(pid)


In my case, I just needed some code to run each minute, but it is part of a Rails app, so I didn't just want to start it with cron every minute (Rails loading is expensive). Neat eh?

Fix Content-Length header on UTF8 with HTTP::Daemon in Perl

It seems that HTTP/Daemon.pm is bogus when it calculate
the header 'Content-Length' when the data contains UTF8 data .

In attachement a patch , to calculate the length in bytes
of the data .

-- 
     ____________________________________________________________
    / Erwan MAS                                                 /\
   | mailto:[EMAIL PROTECTED]                                   |_/
___|________________________________________________________   |
\___________________________________________________________\__/

--- Daemon.pm.orig      2004-12-11 16:13:22.000000000 +0100
+++ Daemon.pm   2006-05-02 22:53:33.660393022 +0200
@@ -436,7 +436,7 @@
            }
        }
        elsif (length($content)) {
-           $res->header("Content-Length" => length($content));
+           $res->header("Content-Length" => bytes::length($content));
        }
        else {
            $self->force_last_request;

Ruby Daemon Module

The following code lets you implement a daemon very easily, and also lets you write cleanup code.

Update: I made some small changes to make it look slightly better.

require 'fileutils'

module Daemon
  WorkingDirectory = File.expand_path(File.dirname(__FILE__))  

  class Base
    def self.pid_fn
      File.join(WorkingDirectory, "#{name}.pid")
    end
    
    def self.daemonize
      Controller.daemonize(self)
    end
  end
  
  module PidFile
    def self.store(daemon, pid)
      File.open(daemon.pid_fn, 'w') {|f| f << pid}
    end
    
    def self.recall(daemon)
      IO.read(daemon.pid_fn).to_i rescue nil
    end
  end
  
  module Controller
    def self.daemonize(daemon)
      case !ARGV.empty? && ARGV[0]
      when 'start'
        start(daemon)
      when 'stop'
        stop(daemon)
      when 'restart'
        stop(daemon)
        start(daemon)
      else
        puts "Invalid command. Please specify start, stop or restart."
        exit
      end
    end
    
    def self.start(daemon)
      fork do
        Process.setsid
        exit if fork
        PidFile.store(daemon, Process.pid)
        Dir.chdir WorkingDirectory
        File.umask 0000
        STDIN.reopen "/dev/null"
        STDOUT.reopen "/dev/null", "a"
        STDERR.reopen STDOUT
        trap("TERM") {daemon.stop; exit}
        daemon.start
      end
    end
  
    def self.stop(daemon)
      if !File.file?(daemon.pid_fn)
        puts "Pid file not found. Is the daemon started?"
        exit
      end
      pid = PidFile.recall(daemon)
      FileUtils.rm(daemon.pid_fn)
      pid && Process.kill("TERM", pid)
    end
  end
end


To use it, you can do something like the following:

class Counter < Daemon::Base
  def self.start
    @a = 0
    loop do
      @a += 1
    end
  end

  def self.stop
    File.open('result', 'w') {|f| f.puts "a = #{@a}"}
  end
end

Counter.daemonize

C - create Process Daemon

// Create a process Daemon

#include <stdio.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{
	/*
	 * Funzione che mi crea un demone
	 */
	
	int pid;
	
	// create - fork 1
	if(fork()) return 0;

	// it separates the son from the father
	chdir("/");
	setsid();
	umask(0);

	// create - fork 2
	pid = fork();

	if(pid)
	{
		printf("Daemon: %d\n", pid);
		return 0;
	}
	
	/****** Codice da eseguire ********/	
	FILE *f;

	f=fopen("/tmp/coa.log", "w");
	
	while(1)
	{
		fprintf(f, "ciao\n");
		fflush(f);
		sleep(2);
	}
	/**********************************/
}

Python - create daemon

// Questa funzione permette di creare un demone in python

def createDaemon():
	'''Funzione che crea un demone per eseguire un determinato programma...'''
	
	import os
	
	# create - fork 1
	try:
		if os.fork() > 0: os._exit(0) # exit father...
	except OSError, error:
		print 'fork #1 failed: %d (%s)' % (error.errno, error.strerror)
		os._exit(1)

	# it separates the son from the father
	os.chdir('/')
	os.setsid()
	os.umask(0)

	# create - fork 2
	try:
		pid = os.fork()
		if pid > 0:
			print 'Daemon PID %d' % pid
			os._exit(0)
	except OSError, error:
		print 'fork #2 failed: %d (%s)' % (error.errno, error.strerror)
		os._exit(1)

	funzioneDemo() # function demo
	
def funzioneDemo():

	import time

	fd = open('/tmp/demone.log', 'w')
	while True:
		fd.write(time.ctime()+'\n')
		fd.flush()
		time.sleep(2)
	fd.close()
	
if __name__ == '__main__':

	createDaemon()

Pre-forking HTTP daemon in Perl

Version 2.. it had issues with zombie / defunct processes on Linux. This is significantly more stable, and I'm currently serving 300,000+ requests a day on something based off of this:

#!/usr/bin/perl

# Basic pre-forking HTTP daemon - version 2
# By Peter Cooper - http://www.petercooper.co.uk/
#
# Inspiration and various rehashed snippetsof code from the Perl 
# cfdaemon engine - http://perl-cfd.sourceforge.net/
#
# You can switch out HTTP::Daemon and make it a pre-forking daemonized 
# 'anything' if you wish..

use HTTP::Daemon;
use HTTP::Status;
use CGI;
use POSIX;

my $totalChildren = 15;				# Number of listening children to keep alive
my $childLifetime = 10;			# Let each child serve up to this many requests
my $logFile = "/tmp/daemon.log";	# Log requests and errors to this file
my %children;							# Store pids of children
my $children = 0;						# Store number of currently active children

&daemonize;								# Daemonize the parent

my $d = HTTP::Daemon->new( LocalPort => 1981, LocalAddr => '127.0.0.1', Reuse => 1, Timeout => 180 ) || die "Cannot create socket: $!\n";

warn ("master is ", $d->url);

&spawnChildren;
&keepTicking;
exit;


# spawnChildren - initial process to spawn the right number of children

sub spawnChildren {
	for (1..$totalChildren) {
		&newChild();
	}
}


# keepTicking - a never ending loop for the parent process which just monitors
# dying children and generates new ones

sub keepTicking {
	while ( 1 ) {
		sleep;
	  	for (my $i = $children; $i < $totalChildren; $i++ ) {
		  &newChild();
		}
	};
}


# newChild - a forked child process that actually does some work

sub newChild {
	my $pid;
	my $sigset = POSIX::SigSet->new(SIGINT);				# Delay any interruptions!
   sigprocmask(SIG_BLOCK, $sigset) or die "Can't block SIGINT for fork: $!";
   die "Cannot fork child: $!\n" unless defined ($pid = fork);
	if ($pid) {
		$children{$pid} = 1;										# Report a child is using this pid
		$children++;												# Increase the child count
		warn "forked new child, we now have $children children";
		return;														# Head back to wait around
	}
	
	my $i;
	while ($i < $childLifetime) {				# Loop for $childLifetime requests
		$i++;
		my $c = $d->accept or last;							# Accept a request, or if timed out.. die early
		$c->autoflush(1);
		logMessage ("connect:". $c->peerhost . "\n");	# We've accepted a connection!
     	my $r = $c->get_request(1) or last;					# Get the request. If it fails, die early

		# Insert your own logic code here. The request is in $r
		# What we do here is check if the method is not GET, if so.. send back a 403.

		my $url = $r->url;
		$url =~ s/^\///g;

     	if ($r->method ne 'GET') { 
			$c->send_error(RC_FORBIDDEN); 
			logMessage ($c->peerhost . " made weird request\n"); 
			redo;
		}
		
		my $response = HTTP::Response->new(200);			# Put together a response
		logMessage ($c->peerhost . " " . $d->url . $url . "\n");	
		$response->content("<html><body>The daemon works! This child has served $i requests.</body></html>");
#				$response->content("document.write('OK $i<br \/>');");
		$response->header("Content-Type" => "text/html");
		$c->send_response($response);							# Send back a basic response
		
		logMessage ("disconnect:" . $c->peerhost . " - ct[$i]\n");		# Log the end of the request
      $c->close;
	}
	
	warn "child terminated after $i requests";
	exit;
}


# REAPER - a reaper of dead children/zombies with exit codes to spare

sub REAPER {                            
	my $stiff;
	while (($stiff = waitpid(-1, &WNOHANG)) > 0) {
		warn ("child $stiff terminated -- status $?");
		$children--;
		$children{$stiff};
	}
	$SIG{CHLD} = \&REAPER;
}        

# daemonize - daemonize the parent/control app

sub daemonize {
	my $pid = fork;												# Fork off the main process
	defined ($pid) or die "Cannot start daemon: $!"; 	# If no PID is defined, the daemon failed to start
	print "Parent daemon running.\n" if $pid;				# If we have a PID, the parent daemonized okay
	exit if $pid;													# Return control to the user

   # Now we're a daemonized parent process!

	POSIX::setsid();												# Become a session leader

	close (STDOUT);												# Close file handles to detach from any terminals
	close (STDIN);
	close (STDERR);

	# Set up signals we want to catch. Let's log warnings, fatal errors, and catch hangups and dying children

	$SIG{__WARN__} = sub {
			&logMessage ("NOTE! " . join(" ", @_));
	};
	
	$SIG{__DIE__} = sub { 
		&logMessage ("FATAL! " . join(" ", @_));
		exit;
	};

	$SIG{HUP} = $SIG{INT} = $SIG{TERM} = sub {			# Any sort of death trigger results in instant death of all
	  my $sig = shift;
	  $SIG{$sig} = 'IGNORE';
	  kill 'INT' => keys %children;
	  die "killed by $sig\n";
	  exit;
	};	
	
	$SIG{CHLD} = \&REAPER;
}

# logMessage - append messages to a log file. messy, but it works for now.

sub logMessage {
	my $message = shift;
	(my $sec, my $min, my $hour, my $mday, my $mon, my $year) = gmtime();
	$mon++;
	$mon = sprintf("%0.2d", $mon);
	$mday = sprintf("%0.2d", $mday);
	$hour = sprintf("%0.2d", $hour);
	$min = sprintf("%0.2d", $min);
	$sec = sprintf("%0.2d", $sec);
	$year += 1900;
	my $time = qq{$year/$mon/$mday $hour:$min:$sec};
	open (FH, ">>" . $logFile);
	print FH $time . " - " . $message;
	close (FH);
}
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS