Saturday, June 19, 2010

Create daemon process in Python

#!/usr/bin/env python
# Filename: daemon.py

# Make the process to run in the background.

__author__ = "Karthikeyan Periasamy"
__version__ = "0.1"
__all__ = ["daemonize"]

# Standard modules
import os               # OS interface functions.
import sys              # System specific functions.
from syslog import *    # Logging functions.

# Daemon parameters
UMASK = 0       # File mode creation mask for the calling process 
WORKDIR = "/"   # The Working directory

# Find the null device /dev/null
if (hasattr(os, "devnull")):
    NULL_DEVICE = os.devnull
else:
    NULL_DEVICE = "/dev/null"
    
# Function
def daemonize (procname):
    openlog (procname, LOG_PID)
    
    try:
        # Fork the child
        syslog (LOG_INFO, "Daemizing")
        syslog (LOG_INFO, "Creating the first child")
        pid = os.fork ()
        
        # Exit from the parent
        if 0 != pid:
            syslog (LOG_INFO, "Parent exiting")
            os._exit (0)

        # Make the child as the leader of the process
        syslog (LOG_INFO, "Child created")
        syslog (LOG_INFO, "Creating a new session")
        os.setsid ()

        # Fork a child again to make sure that no terminal device is connected to it.
        syslog (LOG_INFO, "Creating the second child")
        pid = os.fork ()

        # Exit from the first child
        if 0 != pid:
            syslog (LOG_INFO, "First child exiting")
            os._exit (0)

        # Set the calling process's file mode creation mask
        syslog (LOG_INFO, "Set the calling process's file mode creation mask")
        os.umask (UMASK)

        # Changing working directory to '/' to make sure that
        # the process does not depend on any mounted partition
        # execpt the root of the filesystem
        logmsg = 'Changing working directory to "' + WORKDIR + '" to avoid dependencies'
        syslog (LOG_INFO, logmsg)
        os.chdir (WORKDIR)

        # Close standard input, output and error file descriptors
        syslog (LOG_INFO, "Closing I/O file descriptors")
        os.close (0)
        os.close (1)
        os.close (2)

        # Redirect standard output and errror to /dev/null
        os.open(NULL_DEVICE, os.O_RDWR)
        os.dup2(0, 1)
        os.dup2(0, 2)

    except:
        logmsg = "Unexpected error:" + repr (sys.exc_info()[1])
        syslog (LOG_ERR, logmsg)
        os._exit (1)


# ---------------------------------------------------------------------------
# Main program (for testing)
# ---------------------------------------------------------------------------

if __name__ == '__main__':

    daemonize("daemon_test")
    syslog(LOG_INFO, 'Daemon is sleeping for 10 seconds')

    import time
    for i in range (10):
        syslog(LOG_INFO, 'Sleeping...')
        time.sleep(1)

    syslog(LOG_INFO, 'Daemon exiting')
    sys.exit(0)

Reference: http://code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/

Wednesday, May 26, 2010

Reading and Writing to Excel Spreadsheets in Python

I find it useful.
excel-spreadsheets-and-python

Tuesday, May 25, 2010

Script to log stepwise execution and output of another bash script into syslog

The input arguments for this script would be another script with its input arguments. First, this script stores the stepwise execution and the output of the called bash script into a temporary file. When the called bash script finishes its execution, this script reads the temporary file and logs them into syslog. We are using a temporary file because if we pipe the output of the called script we will lose the true return value of that script.
#!/bin/bash

tmpfile=$(mktemp)
(/bin/bash -x $@ 2>&1) > $tmpfile
retval=$?
cat $tmpfile | logger -t "logger [$1]"
rm -f $$tmpfile

exit $retval
   
  

Tuesday, May 18, 2010

Display code blocks on web page

In my blog, almost all my posts have some code blocks. Whenever I tried to post some code, I had greate difficulties to show the code blocks on the web page as how it should be on the normal editor. Later I realized that we can do it easily with the help of <pre> tag and some more changes and here is the script to do that some more.
#!/bin/bash
usage ()
{
    cat <<EOF
Usage: $(basename $0) <code file>
EOF
exit 1;
}

# Check for the input argument
if [ $# -ne 1 ]; then
    usage
fi

if [ ! -e "$1" ]; then
    echo "ERROR: File ($1) does not exist"
    exit 1
fi

cat <<EOF
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>$1.html</title>
<meta content="MSHTML 6.00.6000.17023" name="GENERATOR">
<meta http-equiv="Content-Type" content="text/html; charset=unicode">
</head>
<body>
<pre>
EOF

sed -e 's/\&/\&amp;/g' -e 's/\"/\&quot;/g' -e 's/˜/\&tilde;/g' -e 's/>/\&gt;/g' -e 's/</\&lt;/g' $1

cat <<EOF
</pre>
</body>
</html>
EOF

Wednesday, May 12, 2010

Script to mount partitions from image file in linux

#!/bin/bash

usage ()
{
    cat <<EOF
Usage: $(basename $0) <image file>
EOF
exit 1;
}

# Check for the input argument
if [ $# -ne 1 ]; then
    usage
fi

sfdisk -l -uS $1 

sfdisk -l -uS $1 2>/dev/null | awk '
           BEGIN {
             i = 1
           }
           /sectors\/track$/ {
             split ($2, array, ":"); 
             imagefile = array[1];
           }
           /^Units = sectors of/ {
             secsize = $5;
           }
           !/#sectors|sectors\/track$|^$|^Units = sectors of/ && $4 != 0 {
             partoffset = secsize * $2;
             cmd = sprintf ("test -e /mnt/tttt%d", i);
             cmd1 = sprintf ("test -d /mnt/tttt%d", i);
             if (system (cmd) != 0)
             {
               cmd = sprintf ("mkdir /mnt/tttt%d 2>/dev/null", i);
               if (system (cmd) != 0)
               {
                 printf ("Error: Could not create the director /mnt/tttt%d.Please try with root privilege.\n", i);
                 exit;
               }
             }
             else if (system (cmd) != 0)
             {
               printf ("Error: /mnt/tttt%d is not a directory.\n", i);
               exit;
             }
             cmd = sprintf ("mount -o loop,offset=%d %s /mnt/tttt%d", partoffset, imagefile, i); 
             if (system (cmd) != 0)
             {
               exit;
             }
             printf ("Mounting: %s ---> /mnt/tttt%d\n", $1, i);
             i++;
           }'

  To run this script:
  root@ubuntu:~# mountImageFile.sh <image file>

  Run this script with root privilege.

Note: This script will not work for large partitions because of the limitation in sfdisk.
Reference: http://lists.samba.org/archive/linux/2005-April/013444.html & manpages awk and sfdisk

Friday, April 30, 2010

Edit anything in your language

Quillpad is a free online Indian language typing tool. You can type in Hindi, Gujarati, Punjabi, Marathi, Telugu, Tamil, Kannada, Malayalam, Bengali and Nepali.

Link: Quillpad

Tuesday, April 20, 2010

My .emacs file (dot emacs) - Emacs Configuration File

;;; Wrapper to make .emacs self-compiling.
(defvar init-top-level t)
(if init-top-level
  (progn


;; ============================
;; Setup syntax, background, and foreground coloring
;; ============================

(set-background-color "Black")
(set-foreground-color "White")
(set-cursor-color "LightSkyBlue")
(set-mouse-color "LightSkyBlue")
(global-font-lock-mode t)
(setq font-lock-maximum-decoration t)

;; User Information
(setq user-full-name "Karthikeyan Periasamy")
(setq user-mail-address "karthikeyan.periasamy@adckrone.com")

;; Tab using spaces
(setq-default indent-tabs-mode nil)

;; ============================
;; Key mappings
;; ============================
(global-set-key [delete] 'delete-char)
(global-set-key [backspace] 'delete-backward-char)

;;; Key binding for sqitching to next and previous buffer
(global-set-key '[C-tab] 'bs-cycle-next) 

;; use F1 key to go to a man page
(global-set-key [f1] 'man)
;; use F2 to save current buffer
(global-set-key [f2] 'save-buffer)
;; use shift+F2 to save current buffer to other file - "Save As"
(global-set-key [(shift f2)] 'write-file)
;; use F3 to check spelling
(global-set-key [f3] 'ispell-word)
;; use F4 key to kill current buffer
(global-set-key [f4] 'kill-this-buffer)
;; use F5 to compile
(global-set-key [f5] 'compile)
;; use F6 to change file mode to hexl
(global-set-key [f6] 'hexl-mode)
;; use F7 to open files in hex mode
(global-set-key [f7] 'hexl-mode-exit)
;; Now bind the delete line function to the F8 key
(global-set-key [f8] 'nuke-line)
;; use F9 to open files in hex mode
(global-set-key [f9] 'hexl-find-file)
;; use F10 to get help (apropos)
(global-set-key [f10] 'apropos)

;; goto line function C-c C-g
(global-set-key [ (control c) (control g) ] 'goto-line)

;; undo and redo functionality with special module
(require 'redo)
(global-set-key (kbd "C-+") 'redo)

;; keys for buffer creation and navigation
(global-set-key [(control x) (control b)] 'iswitchb-buffer)

;; Backup directory to store all files which end with "~"
;; Enable backup files.
(setq make-backup-files t)

;; Enable versioning with default values (keep five last versions, I think!)
(setq version-control t)

;; Save all backup file in this directory.
(setq backup-directory-alist (quote ((".*" . "~/.emacs.d/backups/"))))

;; Set standard indent to 2
(setq standard-indent 2)

;; ============================
;; Mouse Settings
;; ============================

;; mouse button one drags the scroll bar
(global-set-key [vertical-scroll-bar down-mouse-1] 'scroll-bar-drag)

;; setup scroll mouse settings
(defun up-slightly () (interactive) (scroll-up 5))
(defun down-slightly () (interactive) (scroll-down 5))
(global-set-key [mouse-4] 'down-slightly)
(global-set-key [mouse-5] 'up-slightly)

(defun up-one () (interactive) (scroll-up 1))
(defun down-one () (interactive) (scroll-down 1))
(global-set-key [S-mouse-4] 'down-one)
(global-set-key [S-mouse-5] 'up-one)

(defun up-a-lot () (interactive) (scroll-up))
(defun down-a-lot () (interactive) (scroll-down))
(global-set-key [C-mouse-4] 'down-a-lot)
(global-set-key [C-mouse-5] 'up-a-lot)

;; setup font
(set-default-font
 "-Misc-Fixed-Medium-R-Normal--15-140-75-75-C-90-ISO8859-1")

;; No startup screen, if called with file name
;;(setq inhibit-startup-message t)

;; display the current time
(setq display-time-day-and-date t)
(display-time)

;; Show column number at bottom of screen
(setq column-number-mode 1)

;; show a menu only when running within X (save real estate when
;; in console)
;;(menu-bar-mode (if window-system 1 -1))
(menu-bar-mode nil)

;; alias y to yes and n to no
(defalias 'yes-or-no-p 'y-or-n-p)

;; Set the file end-of-line conversion type of the current buffer to Unix
;;(setq buffer-file-coding-system (coding-system-change-eol-conversion
;;                                 buffer-file-coding-system 'unix))

(set-buffer-modified-p t)
(force-mode-line-update)

;; ===========================
;; Behaviour
;; ===========================

;; Pgup/dn will return exactly to the starting point.
(setq scroll-preserve-screen-position 1)

;; don't automatically add new lines when scrolling down at
;; the bottom of a buffer
(setq next-line-add-newlines nil)

;; scroll just one line when hitting the bottom of the window
(setq scroll-step 1)
(setq scroll-conservatively 1)

;; format the title-bar to always include the buffer name
;;(setq frame-title-format "emacs : %b : "(replace-regexp-in-string "\\([\.]\\)" "_" buffer-file-nam)"")
;;(setq frame-title-format "emacs : %b : %f")
;;(setq frame-title-format '(buffer-file-name "%f" ("%b")))
(setq frame-title-format
   '("Emacs : " (buffer-file-name "%f" (dired-directory dired-directory "%b"))))

;; hide the scroll bar
(scroll-bar-mode nil)

;; turn off the toolbar
(if (>= emacs-major-version 21)
    (tool-bar-mode -1))

;; turn on word wrapping in text mode
;;(add-hook 'text-mode-hook 'turn-on-auto-fill)

;; replace highlighted text with what I type rather than just
;; inserting at a point
(delete-selection-mode t)

;; resize the mini-buffer when necessary
(setq resize-minibuffer-mode t)

;; highlight during searching
(setq query-replace-highlight t)

;; highlight incremental search
(setq search-highlight t)

;; Enable uppercase or lowercase conversions
(put 'downcase-region 'disabled nil)
(put 'upcase-region 'disabled nil)

;; Stop ^M's from displaying in system shell window
(add-hook 'comint-output-filter-functions 'shell-strip-ctrl-m nil t)

;; ===========================
;; Buffer Navigation
;; ============================

;; Iswitchb is much nicer for inter-buffer navigation.
(cond ((fboundp 'iswitchb-mode)                ; GNU Emacs 21
       (iswitchb-mode 1))
      ((fboundp 'iswitchb-default-keybindings) ; Old-style activation
       (iswitchb-default-keybindings))
      (t nil))                                 ; Oh well.

;;cfg
(require 'cmssw-mode)

;; ======
;; C/C++ 
;; ======
(defun my-c-mode-common-hook ()
  (turn-on-font-lock)
  (c-set-offset 'substatement-open 0)
  (c-set-offset 'case-label '+)
;;  (c-set-offset 'arglist-cont-nonempty c-lineup-arglist)
  )
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

;; ============================
;; Set up which modes to use for which file extensions
;; ============================
(setq auto-mode-alist
      (append
       '(
         ("\\.h$"             . c++-mode)
         ("\\.dps$"           . pascal-mode)
         ("\\.py$"            . python-mode)
         ("\\.Xdefaults$"     . xrdb-mode)
         ("\\.Xenvironment$"  . xrdb-mode)
         ("\\.Xresources$"    . xrdb-mode)
         ("\\.tei$"           . xml-mode)
         ("\\.php$"           . php-mode)
         ) auto-mode-alist))

;; delete a line
;; First define a variable which will store the previous column position
(defvar previous-column nil "Save the column position")

;; Define the nuke-line function. The line is killed, then the newline
;; character is deleted. The column which the cursor was positioned at is then
;; restored. Because the kill-line function is used, the contents deleted can
;; be later restored by usibackward-delete-char-untabifyng the yank commands.
(defun nuke-line()
  "Kill an entire line, including the trailing newline character"
  (interactive)

  ;; Store the current column position, so it can later be restored for a more
  ;; natural feel to the deletion
  (setq previous-column (current-column))

  ;; Now move to the end of the current line
  (end-of-line)

  ;; Test the length of the line. If it is 0, there is no need for a
  ;; kill-line. All that happens in this case is that the new-line character
  ;; is deleted.
  (if (= (current-column) 0)
    (delete-char 1)

    ;; This is the 'else' clause. The current line being deleted is not zero
    ;; in length. First remove the line by moving to its start and then
    ;; killing, followed by deletion of the newline character, and then
    ;; finally restoration of the column position.
    (progn
      (beginning-of-line)
      (kill-line)
      (delete-char 1)
      (move-to-column previous-column))))


;; Diasble \C-t
(global-unset-key "\C-t")
(global-set-key "\C-t\C-a" 'c-indent-buffer)

;; indent the entire buffer
(defun c-indent-buffer ()
  "Indent entire buffer of C source code."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (< (point) (point-max))
      (c-indent-command)
      (end-of-line)
      (forward-char 1))))

;; set up the compiling options
(setq compile-command "make"
      compilation-ask-about-save nil
      compilation-window-height 10)

))
You have to install some el files.