Sunday, August 15, 2010
Sunday, June 20, 2010
Create daemon process in C
#include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <syslog.h> #include <string.h> #define LOCKFILE "/var/lock/PROCESSNAME" #ifdef CREATE_PID_FILE #define PIDFILE "/var/run/PROCESSNAME.pid" #endif void deamon (void) { pid_t pid, sid; #ifdef CREATE_PID_FILE pid_t child; FILE *pidfp = NULL; #endif int lockfd = -1; /* Create the lock file */ lockfd = open (LOCKFILE, O_RDWR | O_CREAT | O_EXCL, 0640); if (-1 == lockfd) { syslog (LOG_ERR, "ERROR: Unable to create lock file [" LOCKFILE "] -> %s.", strerror(errno)); if (EEXIST == errno) { syslog (LOG_ERR, "ERROR: Another instance of this process might be already running. " "Please kill that process or delete the lock file and try again."); exit (EXIT_FAILURE); } } /* Fork the child */ pid = fork(); if (-1 == pid) { syslog (LOG_ERR, "ERROR: Unable to fork the child process -> %s.", strerror(errno)); /* On failure, delete the lock file */ if (-1 == unlink (LOCKFILE)) { syslog (LOG_ERR, "ERROR: Unable to delete the lock file [" LOCKFILE "] -> %s.", strerror(errno)); } exit (EXIT_FAILURE); } /* Exit from the parent */ if (0 != pid) { exit (EXIT_SUCCESS); } #ifdef CREATE_PID_FILE child = getpid(); pidfp = fopen (PIDFILE, "w"); if (NULL == pidfp) { syslog (LOG_ERR, "ERROR: Unable to open the pid file [" PIDFILE "] -> %s", strerror(errno)); /* On failure, delete the lock file */ if (-1 == unlink (LOCKFILE)) { syslog (LOG_ERR, "ERROR: Unable to delete the lock file [" LOCKFILE "] -> %s.", strerror(errno)); } exit (EXIT_FAILURE); } fprintf (pidfp, "%d\n", child); fclose (pidfp); #endif /* Make the child as the leader of the process */ sid = setsid (); if ((pid_t)-1 == sid) { syslog (LOG_ERR, "ERROR: Unable to create new seesion -> %s", strerror(errno)); /* On failure, delete the lock file and pid file */ if (-1 == unlink (LOCKFILE)) { syslog (LOG_ERR, "ERROR: Unable to delete the lock file [" LOCKFILE "] -> %s.", strerror(errno)); } #ifdef CREATE_PID_FILE if (-1 == unlink (PIDFILE)) { syslog (LOG_ERR, "ERROR: Unable to delete the lock file [" PIDFILE "] -> %s.", strerror(errno)); } #endif exit (EXIT_FAILURE); } /* Set the calling process's file mode creation mask */ umask (0); /* * Changing working directory to '/' to make sure that * the process does not depend on any mounted partition * execpt the root of the filesystem */ if(-1 == chdir ("/")) { syslog (LOG_ERR, "ERROR: Unable to change the directory to \"/\" -> %s", strerror(errno)); /* On failure, delete the lock file and pid file */ if (-1 == unlink (LOCKFILE)) { syslog (LOG_ERR, "ERROR: Unable to delete the lock file [" LOCKFILE "] -> %s.", strerror(errno)); } #ifdef CREATE_PID_FILE if (-1 == unlink (PIDFILE)) { syslog (LOG_ERR, "ERROR: Unable to delete the lock file [" PIDFILE "] -> %s.", strerror(errno)); } #endif exit (EXIT_FAILURE); } /* Close standard input file descriptor */ close (0); /* Redirect standard output and errror to /dev/null */ freopen ( "/dev/null", "w", stdout); freopen ( "/dev/null", "w", stderr); }Reference: http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html
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
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
Labels:
Bash
,
logger
,
mktemp
,
Shell scripting
,
syslog
,
temporary file
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/\&/\&/g' -e 's/\"/\"/g' -e 's/˜/\˜/g' -e 's/>/\>/g' -e 's/</\</g' $1 cat <<EOF </pre> </body> </html> EOF
Labels:
code block on web page
,
HTML
,
HTML Special characters
,
pre html tag
,
sed
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.
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
Labels:
awk
,
image file
,
linux
,
loop device
,
mount
,
partition
,
partitioned image file
,
sfdisk
Subscribe to:
Posts
(
Atom
)