Saturday, October 30, 2010

AVL tree - self-balancing binary search tree

In an AVL tree, the heights of the two child subtrees of any node differ by at most one; therefore, it is also said to be height-balanced. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations.

Psuedo code:
IF tree is right heavy
{
  IF tree's right subtree is left heavy
  {
     Perform Double Left rotation
  }
  ELSE
  {
     Perform Single Left rotation
  }
}
ELSE IF tree is left heavy
{
  IF tree's left subtree is right heavy
  {
     Perform Double Right rotation
  }
  ELSE
  {
     Perform Single Right rotation
  }
}

Reference:
http://en.wikipedia.org/wiki/AVL_tree
http://oopweb.com/Algorithms/Documents/AvlTrees/Volume/AvlTrees.htm

Monday, October 25, 2010

Signal handler is not your regular function

Signal handler is a function which will be called when the program receives a signal. Most of the signals have their own default handlers and for few the parent program should handle/ignore this signal explicitly. In case of SIGCHLD, if the parent process should define the handler explicitly and wait for the child to exit (we can use SIGIGN too and no need to wait),otherwise the child process will become zombie.

Signal handler can not do everything what any normal function can do. It can call the functions and system calls which are async-safe.
This is the list of async-safe fuctions and system calls,

_Exit(), _exit(), abort(), accept(), access(), aio_error(), aio_return(), aio_suspend(), alarm(), bind(), cfgetispeed(), cfgetospeed(), cfsetispeed(), cfsetospeed(), chdir(), chmod(), chown(), clock_gettime(), close(), connect(), creat(), dup(), dup2(), execle(), execve(), fchmod(), fchown(), fcntl(), fdatasync(), fork(), fpathconf(), fstat(), fsync(), ftruncate(), getegid(), geteuid(), getgid(), getgroups(), getpeername(), getpgrp(), getpid(), getppid(), getsockname(), getsockopt(), getuid(), kill(), link(), listen(), lseek(), lstat(), mkdir(), mkfifo(), open(), pathconf(), pause(), pipe(), poll(), posix_trace_event(), pselect(), raise(), read(), readlink(), recv(), recvfrom(), recvmsg(), rename(), rmdir(), select(), sem_post(), send(), sendmsg(), sendto(), setgid(), setpgid(), setsid(), setsockopt(), setuid(), shutdown(), sigaction(), sigaddset(), sigdelset(), sigemptyset(), sigfillset(), sigismember(), sleep(), signal(), sigpause(), sigpending(), sigprocmask(), sigqueue(), sigset(), sigsuspend(), sockatmark(), socket(), socketpair(), stat(), symlink(), sysconf(), tcdrain(), tcflow(), tcflush(), tcgetattr(), tcgetpgrp(), tcsendbreak(), tcsetattr(), tcsetpgrp(), time(), timer_getoverrun(), timer_gettime(), timer_settime(), times(), umask(), uname(), unlink(), utime(), wait(), waitpid(), and write().

Ref : http://beej.us/guide/bgipc/output/html/singlepage/bgipc.html#signals

Sunday, October 24, 2010

[screen] - Access multiple separate terminal sessions inside a single terminal window or remote terminal session

Its very useful if we want to work in multiple system (office and home PC). We won't lose the shell session connection.

Ref:
http://www.rackaid.com/resources/linux-screen-tutorial-and-how-to/
http://en.wikipedia.org/wiki/GNU_Screen

Prime numbers

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include <string.h>
#include <errno.h>

#define ERRNUM -1

typedef enum bool {
  FALSE =0,
  TRUE
} e_bool;

typedef enum stauts {
  FAILURE = 0,
  SUCCESS
} e_status;

typedef struct list* tsp_list;
struct list{
  unsigned int val;
  unsigned int index;
  tsp_list next;
};

e_status Append (unsigned int num, tsp_list *list)
{
  tsp_list lsp_primeNode = NULL;
  lsp_primeNode = (tsp_list) calloc (1, sizeof (struct list));
  if (NULL == lsp_primeNode)
  {
    fprintf (stderr, "ERROR: memory allocation failed.\n");
    return FAILURE;
  }
  lsp_primeNode->val = num;
  lsp_primeNode->next = NULL;

  if (NULL == *list)
  {
    *list = lsp_primeNode;
    lsp_primeNode->index = 1;
  }
  else
  {
    tsp_list node = *list;
    while (NULL != node->next)
    {
      node = node->next;
    }

    node->next = lsp_primeNode;
    lsp_primeNode->index = node->index + 1;
  }

  return SUCCESS;
}


e_bool IsPrime (unsigned int num, tsp_list list)
{
  if (1 >= num)
  {
    return FALSE;
  }

  switch (num)
  {
    case 2:
    case 3:
      return TRUE;
    default:
      {
        unsigned int lv_max_limit = (unsigned int) sqrt (num);
        
        while (list && list->val <= lv_max_limit)
        {
          if (0 == num % list->val)
          {
            return FALSE;
          }
          list = list->next;
        }
        return TRUE;
      }
  }
}

void GetPrimeList (tsp_list *list, unsigned count)
{
  unsigned int i = 2;
  unsigned int index = 1;
  struct timeval start;
  struct timeval end;
  struct timeval diff;

  if(-1 == gettimeofday(&start, NULL))
  {
    fprintf (stderr, "ERROR: %s\n", strerror (errno));
    return;
  }

  for (; i && 0 < count; i++)
  {
    if (TRUE == IsPrime (i, *list))
    {
      if(-1 == gettimeofday(&end, NULL))
      {
        fprintf (stderr, "ERROR: %s\n", strerror (errno));
        return;
      }

      /* Ref [http://www.linuxquestions.org/questions/programming-9/how-to-calculate-time-difference-in-milliseconds-in-c-c-711096] */
      diff.tv_sec =end.tv_sec - start.tv_sec ;
      diff.tv_usec=end.tv_usec - start.tv_usec;

      if(diff.tv_usec<0)
      {
        diff.tv_usec+=1000000;
        diff.tv_sec -=1;
      }

      printf ("%d (index: %d) (Time taken: %f sec)\n", i, index++, (float)(1000000LL*diff.tv_sec + diff.tv_usec)/1000000);
      
      if (FAILURE == Append (i, list))
      {
        return;
      }
      else
      {
        count --;
      }
    }
  }
}

int main (int argc, char *argv[])
{
  tsp_list primeList = NULL;
  int dig = 0;

  if ( 2 != argc)
  {
    return 0;
  }

  GetPrimeList (&primeList, (int) atoi(argv[1]));

  return 0;
}

Monday, October 18, 2010

Find the permutation and combination for a given string

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define ERRNUM -1
#define SUCCESS 0

#define TRUE 1
#define FALSE 0

#define TOTAL_ALPHA 26

/* Function   : permutations
 * Args       : str [IN]
 *              index [IN]
 *              result [IN/OUT]
 * Description: Function will print all the permutations and combinations of a given string 
 *              without repeated patterns. PnC(ABC) = { A+PnC(BC), B+PnC(CA), C+PnC(AB) } 
 * Note       : This "without repeated patterns" will not work for non-alpha characters [TBD]. 
 */
int permutations (char *str, int index, char *result)
{
  char *temp = NULL;           // To store the given string for processing
  int len = strlen (str);      // Length of the given string
  int count = 0;               // Counter variable used in the loop
  int j = 0;                   // Temporary variable
  char found[52] = {0};        // To check the variable to check the duplicate characters to avoid duplicate patterns

  /* Allocate memory for the temp variable to store the given string for processing.
   * So that the given string will not change. 
   */
  temp = (char *) calloc (len+1, sizeof (char));
  if (NULL == temp)
  {
    fprintf (stderr, "Memory allocation failed.\n");
    return ERRNUM;
  }

  /* Copy the given string into the temporary variable */
  strcpy (temp, str);

  /* Traverse through the string and find the permutations and combinations of the substring 
   * PnC(ABC) = { A+PnC(BC), B+PnC(CA), C+PnC(AB) } 
   */
  for (count=0; count < len; count++)
  {
    char ch = 0;
    
    *(result + index) = *temp;
    if (1 == len)
    {
      /* We can store in an array of string or a stack */
      printf ("%s\n", result);
    }
    else
    {
      if (isupper (*temp))
      {
        
        if (FALSE == found [TOTAL_ALPHA + (*temp) - 'A'])
        {
          found [TOTAL_ALPHA + (*temp) - 'A'] = TRUE;
        }
        else
        {
          /* Its a duplicate character */
          goto NEXT;
        }
      }
      else if (islower (*temp))
      {
        if (FALSE == found [(*temp) - 'a'])
        {
          found [(*temp) - 'a'] = TRUE;
        }
        else
        {
          /* Its a duplicate character */
          goto NEXT;
        }
      }
      
      /* We can store in an array of string or a stack */
      for (j=0; j<=index; j++)
      {
        printf ("%c", *(result+j));
      }
      printf ("\n");

      /* Find the permutations and combinations for the substring too */
      if (ERRNUM == permutations (temp+1, index+1, result))
      {
        return ERRNUM;
      }

    NEXT:
      ch = *temp;
      memcpy (temp, temp+1, len-1);
      temp[len-1] = ch;
    }
  }

  /* Free the allocated memory for the temporary variable */
  free (temp);

  return SUCCESS;
}

int main (int argc, char *argv[])
{
  char *result = NULL;        // Variable to store the result for printing 
  int retVal = SUCCESS;       // Variable to stroe the return value

  // No code to check/validate the input [TBD].

  if (NULL == result)
  {
    result = (char *) calloc (strlen (argv[1])+1, sizeof (char));
    if (NULL == result)
    {
      fprintf (stderr, "Memory allocation failed.\n");
      return ERRNUM;
    }
  }

  retVal = permutations (argv[1], 0, result);
  
  free (result);
    
  return retVal;
}
The results:
prompt$ ./permutationsNconbination ABC

A

AB

ABC

AC

ACB

B

BC

BCA

BA

BAC

C

CA

CAB

CB

CBA

prompt$ ./permutationsNconbination AAB

A

AA

AAB

AB

ABA

B

BA

BAA

prompt$ ./permutationsNconbination AAA

A

AA

AAA

prompt$

Wednesday, September 15, 2010

Processing input arguments in C program

Parsing Sort options:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

void usage (const char *programName)
{
  printf ("Usage: %s [-kldeh]\n"
          "          -k <val_k>   Value for the the option -k\n"
          "          -l <val_l>   Value for the the option -l\n"
          "          -d           Does not have any value\n"
          "          -e           Does not have any value\n"
          "          -h           Print this message\n\n",
          programName);

  exit (EXIT_SUCCESS);
}

int main (int argc, char **argv)
{
  char *val_k = NULL;
  int index = 0;
  int c = 0;
  
  if (1 == argc)
  {
    printf ("This tool needs at lease one input arguments.\n");
    usage (argv[0]);
  }

  /* Check the input arguments/options */
  while (-1 != (c = getopt (argc, argv, "k:l:deh")))
  {
    switch (c)
    {
      case 'k':
        /* Assign the optarg pointer to a local variable for further use. */
        val_k = optarg;
        printf ("value for the option [k] is \"%s\"\n", val_k);
        break;
      case 'l':
        /* We can use the variable optarg directly too. */
        printf ("value for the option [l] is \"%s\"\n", optarg);
        break;
      case 'd':
        printf ("option [d] is given.\n");
        break;
      case 'e':
        printf ("option [e] is given.\n");
        break;
      case 'h':
        usage (argv[0]);
      case '?':
        if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        usage (argv[0]);
      default:
        abort ();
    }
  }

  for (index = optind; index < argc; index++)
  {
    printf ("Extra arguments [%d] --> %s\n", index, argv[index]);
  }

  return 0;
}


Parsing Long options:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <getopt.h>

static struct option options[] = {
  /* These options set a flag.   */
  {"option_k", 1, 0, 'k'},
  {"option_l", 1, 0, 'l'},
  {"option_d", 0, 0, 'd'},
  {"option_e", 0, 0, 'e'},
  {"help", 0, 0, 'h'},
  {0, 0, 0, 0}
};

void usage (const char *programName)
{
  printf ("Usage: %s [-kldeh]\n"
          "          -k or --option_k <val_k>   Value for the the option -k\n"
          "          -l or --option_l <val_l>   Value for the the option -l\n"
          "          -d or --option_d           Does not have any value\n"
          "          -e or --option_e           Does not have any value\n"
          "          -h or --help               Print this message\n\n",
          programName);

  exit (EXIT_SUCCESS);
}

int main (int argc, char **argv)
{
  char *val_k = NULL;
  int index = 0;
  int c = 0;
  int option_index = 0;

  if (1 == argc)
  {
    printf ("This tool needs at lease one input arguments.\n");
    usage (argv[0]);
  }

  /* Check the input arguments/options */
  while (-1 != (c = getopt_long (argc, argv, "k:l:deh",
                                 options, &option_index)))
  {
    switch (c)
    {
      case 'k':
        /* Assign the optarg pointer to a local variable for further use. */
        val_k = optarg;
        printf ("value for the option [k] is \"%s\"\n", val_k);
        break;
      case 'l':
        /* We can use the variable optarg directly too. */
        printf ("value for the option [l] is \"%s\"\n", optarg);
        break;
      case 'd':
        printf ("option [d] is given.\n");
        break;
      case 'e':
        printf ("option [e] is given.\n");
        break;
      case 'h':
        usage (argv[0]);
      case '?':
        if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        usage (argv[0]);
      default:
        abort ();
    }
  }

  for (index = optind; index < argc; index++)
  {
    printf ("Extra arguments [%d] --> %s\n", index, argv[index]);
  }

  return 0;
}

Ref: http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_22.html

awk - One of the best tools in linux

I was searching for a tool/command in linux to remove all the duplicate lines from a file without sort the lines. And i came across this link (see the link below)...Its really amazing. We can do lots and lots of things using awk. Its one of the mostpowerful tools for file/string processing. I hope it will be useful for most of the software developers and testers. One more good thing is that awk is available for windows too.

Link: http://kaneda.bohater.net/faq/awk1line.txt.
The latest version of this file is here.

Processing input arguments in bash shell scripting

 
# Function to print the usage of this script
Usage ()
{
    cat <<EOF
Usage: `basename $0` options [-kld]
          -k <val_k>   Value for the the option -k
          -l <val_l>   Value for the the option -l
          -d           Does not have any value
          -e           Does not have any value
          -h           Print this message
EOF
exit $E_OPTERROR
}
 
# Check for input arguments. If no arguments given, print the usage.
if [ $# -eq 0 ]; then
    Usage
fi
 
while getopts ":k:l:de" Option
do
    case $Option in
        k ) echo "value for the option [k] is \"$OPTARG\""
            ;;
        l ) echo "value for the option [l] is \"$OPTARG\""
            ;;
        d ) echo "option [d] is given."
            ;;
        e ) echo "option [e] is given."
            ;;
        h ) Usage
            ;;
        * ) echo "Invalid input option"
            Usage
            ;;
    esac
done

# To get the arguments other than the option given in the usage
shift $(($OPTIND - 1))
 
for i in $*
do
    echo "Extra inputs given -> \"$i\""
done

exit 0

Sunday, August 15, 2010

Create pdf with pictures (one in each page) using tex



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/

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.

Wednesday, March 10, 2010

Pocket Linux Guide


The Linux Documentation Project


This document takes baby steps to explains how to build a small diskette-based GNU/Linux system. This is a very good starting place for Linux newbies to understand how basic linux system works.

Get information about all the network interfaces in linux

This program lists all active network interfaces in the system with associated IP address, MAC address and the subnetmask.
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#define __KERNEL__
#include <asm/types.h>
#undef __KERNEL__

#include <linux/ethtool.h>
#include <linux/sockios.h>

#include <net/if.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>

/* this is straight from beej's network tutorial. It is a nice wrapper
 * for inet_ntop and helpes to make the program IPv6 ready
 */
char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen)
{
  switch(sa->sa_family) {
    case AF_INET:
      inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr), s, maxlen);
      break;

    case AF_INET6:
      inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr), s, maxlen);
      break;

    default:
      strncpy(s, "Unknown AF", maxlen);
      return NULL;
  }

  return s;
}

int main (int argc, char **argv)
{
  char          buf[1024] = {0};
  struct ifconf ifc = {0};
  struct ifreq *ifr = NULL;
  int           sck = 0;
  int           nInterfaces = 0;
  int           i = 0;
  struct ifreq ifr_subnet;
  struct sockaddr *addr_subnet = NULL;

  /* Get a socket handle. */
  sck = socket(AF_INET, SOCK_DGRAM, 0);
  if(-1 == sck) {
    perror("socket");
    return 1;
  }

  /* Query available interfaces. */
  ifc.ifc_len = sizeof(buf);
  ifc.ifc_buf = buf;
  if(-1 == ioctl(sck, SIOCGIFCONF, &ifc)) {
    perror("ioctl(SIOCGIFCONF)");
    close (sck);
    return 1;
  }

  /* Iterate through the list of interfaces. */
  ifr = ifc.ifc_req;
  nInterfaces = ifc.ifc_len / sizeof(struct ifreq);
  for(i = 0; i < nInterfaces; i++)
  {
    struct ifreq *item = &ifr[i];

    /* Show the device name and IP address */
    struct sockaddr *addr = &(item->ifr_addr);
    char ip[INET6_ADDRSTRLEN];
    printf("%s: IP %s",
           item->ifr_name,
           get_ip_str(addr, ip, INET6_ADDRSTRLEN));

    /* Get the MAC address */
    if(-1 == ioctl(sck, SIOCGIFHWADDR, item)) {
      perror("ioctl(SIOCGIFHWADDR)");
      close (sck);
      return 1;
    }

    /* display result */
    printf(", MAC %.2x:%.2x:%.2x:%.2x:%.2x:%.2x ",
           (unsigned char)item->ifr_hwaddr.sa_data[0],
           (unsigned char)item->ifr_hwaddr.sa_data[1],
           (unsigned char)item->ifr_hwaddr.sa_data[2],
           (unsigned char)item->ifr_hwaddr.sa_data[3],
           (unsigned char)item->ifr_hwaddr.sa_data[4],
           (unsigned char)item->ifr_hwaddr.sa_data[5]);

    /* Reset the memory allocated for ifreq */
    memset (&ifr_subnet, 0, sizeof (struct ifreq));

    /* Update interface name into ifreq */
    strcpy (ifr_subnet.ifr_name, item->ifr_name);

    /* Call ioctl function */
    if(-1 == ioctl (sck, SIOCGIFNETMASK, &ifr_subnet ))
    {
      perror("ioctl(SIOCGIFNETMASK)");
      close (sck);
      return 1;
    }
    addr_subnet = &(ifr_subnet.ifr_addr);
    printf("SubnetMask: %s\n", get_ip_str(addr_subnet, ip, INET6_ADDRSTRLEN));
  }

  close (sck);
  return 0;
}

Reference: http://www.adamrisi.com/?p=84

Tuesday, March 9, 2010

Simple PING implementation in C

#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/signal.h>
#include <string.h>

#define DEFDATALEN      56
#define MAXIPLEN        60
#define MAXICMPLEN      76

static char *hostname = NULL;

static int in_cksum(unsigned short *buf, int sz)
{
  int nleft = sz;
  int sum = 0;
  unsigned short *w = buf;
  unsigned short ans = 0;
  
  while (nleft > 1) {
    sum += *w++;
    nleft -= 2;
  }
  
  if (nleft == 1) {
    *(unsigned char *) (&ans) = *(unsigned char *) w;
    sum += ans;
  }
  
  sum = (sum >> 16) + (sum & 0xFFFF);
  sum += (sum >> 16);
  ans = ˜sum;
  return (ans);
}

static void noresp(int ign)
{
  printf("No response from %s\n", hostname);
  exit(0);
}

static void ping(const char *host)
{
  struct hostent *h;
  struct sockaddr_in pingaddr;
  struct icmp *pkt;
  int pingsock, c;
  char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
  
  if ((pingsock = socket(AF_INET, SOCK_RAW, 1)) < 0) {       /* 1 == ICMP */
    perror("ping: creating a raw socket");
    exit(1);
  }
  
  /* drop root privs if running setuid */
  setuid(getuid());
  
  memset(&pingaddr, 0, sizeof(struct sockaddr_in));
  
  pingaddr.sin_family = AF_INET;
  if (!(h = gethostbyname(host))) {
    fprintf(stderr, "ping: unknown host %s\n", host);
    exit(1);
  }
  memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
  hostname = h->h_name;
  
  pkt = (struct icmp *) packet;
  memset(pkt, 0, sizeof(packet));
  pkt->icmp_type = ICMP_ECHO;
  pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
  
  c = sendto(pingsock, packet, sizeof(packet), 0,
             (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
  
  if (c < 0 || c != sizeof(packet)) {
    if (c < 0)
      perror("ping: sendto");
    fprintf(stderr, "ping: write incomplete\n");
    exit(1);
  }
  
  signal(SIGALRM, noresp);
  alarm(2);                                     /* give the host 5000ms to respond */
  /* listen for replies */
  while (1) {
    struct sockaddr_in from;
    size_t fromlen = sizeof(from);
    
    if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
                      (struct sockaddr *) &from, &fromlen)) < 0) {
      if (errno == EINTR)
        continue;
      perror("ping: recvfrom");
      continue;
    }
    if (c >= 76) {                   /* ip + icmp */
      struct iphdr *iphdr = (struct iphdr *) packet;
      
      pkt = (struct icmp *) (packet + (iphdr->ihl << 2));      /* skip ip hdr */
      if (pkt->icmp_type == ICMP_ECHOREPLY)
        break;
    }
  }
  printf("%s is alive!\n", hostname);
  return;
}

int main ()
{
  ping ("192.168.1.2");

}

Reference: http://www.koders.com/c/fid30EA22902AFF5800481BBC6F65DADCDAF92D6E37.aspx

Monday, March 8, 2010

Add new option in configure script in autobuild system

Example:
To get a new option "--with-unit-test" when you run "./configure --help"

Optional Packages:
  --with-unit-test        Create binary to unit test the library package
                          (default is no)

add the following block in "configure.ac"

AC_MSG_CHECKING([--with-unit-test])
AC_ARG_WITH(unit-test,
        AC_HELP_STRING([--with-unit-test], [Create binary to unit test the library package (default is no)]),
        [unittest="yes"],
        [unittest="no"]
)
AM_CONDITIONAL(UNIT_TEST, test "$unittest" = "yes")
AC_MSG_RESULT([$unittest])


and you Makefile.am will look like this,

bindir = $(prefix)/usr/local/bin
libdir = $(prefix)/usr/local/lib

if UNIT_TEST
bin_PROGRAMS = unittest
unittest_SOURCES = source1.c \
                      Source2.c
unittest_CFLAGS = -I@top_srcdir@/include \
                     -DUNIT_TEST
unittest_LDFLAGS =
else
lib_LTLIBRARIES           = libunittest.la
libunittest_la_SOURCES = source2.c \
                         source3.c
libunittest_la_CFLAGS = -I@top_srcdir@/include
libunittest_la_LDFLAGS = -version-info 0:1:0
endif


and take care of UNIT_TEST macro check in the source code.

How to create self-Extracting script

It involves 3 steps,
  1. Create Payload
  2. Create Installer script
  3. Packaging
Create Payload:
This is a tar ball  in which all the installable binaries, libraries, script files, configuration files, etc will be placed in the same file hierarchy of the target board considering the base directory of the tar ball is the installation directory on the target board.

periask@ubuntu:~$ mkdir -vp packaging/Payload
mkdir: created directory `packaging
mkdir: created directory `packaging/Payload'
periask@ubuntu:~$ cd packaging/Payload
periask@ubuntu:~/packaging/Payload$ cp --preserve=mode -rl <installables> .
periask@ubuntu:~/packaging/Payload$ tar zcf ../Payload.tar.gz .
periask@ubuntu:~/packaging/Payload$ cd ..
periask@ubuntu:~/packaging$

Create Installer Script:
Copy the below content and create "installer" file in "packaging" directory.

#!/bin/bash

# Get the starting point of the tar ball
SKIP=`awk '/^__ARCHIVE__/ { print NR + 1; exit 0; }' $0`

# Do pre-installation steps here.

# Extracting the tar ball Which is appended to this file
tail -n "+$SKIP" $0 >/dev/null 2>&1
if [ $? -eq 0 ]; then
    tail -n +$SKIP $0 | gunzip -c | tar -C / -xvf -
else
    tail +$SKIP $0 | gunzip -c | tar -C / -xvf - 
fi

# Do post-installation steps here.

exit 0

__ARCHIVE__

Note: There should not be any space  after "__ARCHIVE__" and should be a new line after "__ARCHIVE__".

Packaging:
Concatenate the file "installer" and "Payload.tar.gz" and create the package file.

periask@ubuntu:~/packaging$ cat installer Payload.tar.gz > Package-Version.sh
periask@ubuntu:~/packaging$ chmod +x Package-Version.sh

Installer for your package "Package-Version.sh" is ready.

Source: Linux Journal

Avahi-autoipd

It is an Zeroconf implementation of Avahi which facilitates configuration of a network element automatically on the local network in the absence of DHCP server. It uses a special address range 169.254.0.0/16 and prefix fe80::/16 for IPV4 and IPV6 link-local addressing respectively. When the autoipd daemon starts, it generates an IP address randomly using the MAC address information and announces its new IP using ARP probe to find address conflict. If the given address is being used by another network element, it generates a new IP and does ARP probe till it successfully claims the address. It stores this IP address in a file for persistence across network restart (file location on linux machine will be "/var/lib/avahi-autoipd/<mac_address>"). To configure this address to be routable on the local link, autoipd adds routing rule for this IP address in the routing table.

Source: RFC3927, Avahi