Wednesday, 4 December 2013

C program to demonstrate working of Turing Machine

Leave a Comment
        Turing machine is a imaginary device with infinite tape which manipulates the symbols on tape to get required result on the basis of specified rule. Instead of going in a theoretical detail we will concentrate on practical implementation of it.
        Here we are going to demonstrate "n mod 2" implementation using Turing machine. In this example we take input from user (number 'n') and then create an array with size 'n+2' containing "NULL" followed by all 1s followed by "NULL". At first pointer is pointing to the left most element of array which is initial of array. Then by traversing right go to the element of array which is "NULL" and stop at that point as shown in the figure below. Then traverse left. If '1' comes while traversing left, replace '1' with "NULL" and alter the flag between 0 and 1. At last if you get flag as '1' then it can be considered as ODD number otherwise (flag=0 i.e. remain as it is) it is EVEN number.
       Download program NMOD2.c.


#include"stdio.h"
#include"stdlib.h"
int main()
{
 int i,n,flag=0;
 char *ptr;
 printf("\n Enter number\n");
 scanf("%d",&n);
 ptr= (char *)malloc((n+2)*sizeof(char));

 for(i = 0; i < n+2; i++)
 {
  if(i == 0 || i == n+1)
  {
   ptr[i]='\0';
  }
  else
  {
   ptr[i]='1';
  }
 }

 ptr=ptr+1;
 while(*ptr != '\0')
 {
  ptr = ptr+1;
 }
 ptr = ptr-1;

 while(*ptr != '\0')
 {
  if(*ptr == '1')
  *ptr='\0';

  if(flag == 0)
  {
   flag = 1;
  }

  else if(flag == 1)
  {
   flag = 0;
  }
  else
  {
  }
  ptr=ptr-1;
 }
 
 if(flag == 1)
  printf("This is ODD Number\n");
 else
  printf("This is EVEN Number\n" );
 return 0;
}


Read More...

Friday, 25 October 2013

Calculate time in C or CPP program

Leave a Comment
      There are many methods to calculate time taken by part of execution or whole program in gcc as mention below.
Calculate Time in C
       Out of this time() function gives the accuracy up-to seconds. But generally we require accuracy in micro or nano seconds to check the little difference. So we are going to see the time calculation using clock_gettime() and gettimeofday() function for well known application matrix multiplication.
      The programs matrix_mul_gettimeofday.c given below show the time calculated using gettimeofday() function

#include"stdio.h"
#include"sys/time.h"
#include"stdlib.h"
#define N 4000
#define X 300
#define Y 200

int main()
{
 int sum = 0,i,j,k;
 int **mat1; //declared mat1[X][N]
 int **mat2; //declare mat2[N][Y]
  int **mat_res; //resultant matrix become mat_res[X][Y]
  struct timeval tim;
  double t1,t2,result;
  
  /*----------------------------------------------------*/
 //create array of pointers(Rows)
  mat1 =(int **) malloc(X*sizeof(int*));
  mat2 =(int **)malloc(N*sizeof(int*));
  mat_res=(int **)malloc(X*sizeof(int*));
  /*----------------------------------------------------*/
  
  /*--------------------------------------------------------------------------------*/
 //allocate memory for each Row pointer
  for(i=0; i < X; i++)
  {
   mat1[i] = (int *) malloc(N * sizeof(int));
   mat_res[i] = (int *) malloc(Y * sizeof(int));
  }
  
  for(i = 0; i < N; i++)
  mat2[i] = (int *) malloc(Y * sizeof(int));
  /*--------------------------------------------------------------------------------*/
  
  for(i = 0; i < X; i++)
 {
  for(j = 0; j < N; j++)
  {
   mat1[i][j] = 1; 
  }
 }
 
 for(i = 0; i < N; i++)
 {
  for(j = 0; j < Y; j++)
  {
   mat2[i][j] = 2;
  }
 }
 //------------------calculate Start time------------------------
 gettimeofday(&tim, NULL);
 t1 = tim.tv_sec + (tim.tv_usec/1000000.0);
 //--------------------------------------------------------------
 
  for(i = 0; i < X; i++)
  {
   for(j = 0; j < Y;j++)
   {
    sum=0;
    for(k = 0; k < N; k++)
    {
     sum = sum + mat1[i][k] * mat2[k][j];
    }
    mat_res[i][j] = sum;
   }
  }
 //---------------calculate End time-----------------------------
  gettimeofday(&tim, NULL);
 t2 = tim.tv_sec + (tim.tv_usec/1000000.0);
 //--------------------------------------------------------------

 // result = End_time - Start_time
 result = t2 - t1;
  for(i = 0; i < X; i++)
  {
   for(j = 0; j < Y; j++)
   {
    printf("%d\t",mat_res[i][j]);
   }
   printf("\n");
  }
  printf("time taken =%f\n",result);
  return 0;
}

Compile:
gcc matrix_mul_gettimeofday.c -o exec
Run:
./exec

The program matrix_mul_clock_gettime.c given below will show how to calculate time using clock_gettime() function


#include"stdio.h"
#include"time.h"
#include"math.h"
#include"stdlib.h"
#define N 4000
#define X 300
#define Y 200

int main()
{
 int sum = 0,i,j,k;
 int **mat1; //declared mat1[X][N]
 int **mat2; //declare mat2[N][Y]
  int **mat_res; //resultant matrix become mat_res[X][Y]
  struct timespec start,stop;
  double t1=0,t2=0,result=0;
  
  /*----------------------------------------------------*/
 //create array of pointers(Rows)
  mat1 =(int **) malloc(X*sizeof(int*));
  mat2 =(int **)malloc(N*sizeof(int*));
  mat_res=(int **)malloc(X*sizeof(int*));
  /*----------------------------------------------------*/
  
  /*--------------------------------------------------------------------------------*/
 //allocate memory for each Row pointer
  for(i=0; i < X; i++)
  {
   mat1[i]=(int *)malloc(N*sizeof(int));
   mat_res[i]=(int *)malloc(Y*sizeof(int));
  }
  
  for(i = 0; i < N; i++)
  mat2[i]=(int *)malloc(Y*sizeof(int));
  /*--------------------------------------------------------------------------------*/
  
  for(i = 0; i < X; i++)
 {
  for(j = 0; j < N; j++)
  {
   mat1[i][j] = 1; 
  }
 }
 
 for(i = 0; i < N; i++)
 {
  for(j = 0; j < Y; j++)
  {
   mat2[i][j] = 2;
  }
 }
 //------------------calculate Starting time----------------------
 clock_gettime(CLOCK_REALTIME,&start);
 t1 = start.tv_sec + (start.tv_nsec/pow(10,9));
 //--------------------------------------------------------------
 
  for(i = 0; i < X; i++)
  {
   for(j = 0; j < Y;j++)
   {
    sum=0;
    for(k = 0; k < N; k++)
    {
     sum = sum + mat1[i][k] * mat2[k][j];
    }
    mat_res[i][j] = sum;
   }
  }
 //---------------calculate End time-------------------------
  clock_gettime(CLOCK_REALTIME,&stop);
 t2 = stop.tv_sec + (stop.tv_nsec/pow(10,9));
 //--------------------------------------------------------------
 // result = End_time - Start_time
 result = t2 - t1;
  for(i = 0; i < X; i++)
  {
   for(j = 0; j < Y; j++)
   {
    printf("%d\t",mat_res[i][j]);
   }
   printf("\n");
  }
  printf("\ntime taken =\t %lf\n",result);
  return 0;
}
  
In this program CLOCK_REALTIME means choose best wall clock timing of machines which is defined in time.h header file.
compile:
gcc matrix_mul_clock_gettime.c -o exec -lm
Run:
./exec
    Read More...

    Tuesday, 15 October 2013

    Matrix Multiplication in MPI

    1 comment
             Message Passing Interface (MPI) is used for distributed computing. MPI is not a language it is library used to fork multiple processes and communicate between them using efficient protocols. MPI has many distributions such as MPICH, MVAPICH, OpenMPI etc.
             The program below explains simple matrix multiplication using point to point communication in MPI.
             Let's consider matrix1 with 5x4 and another matrix2 with 4x3 dimension after matrix multiplication the resultant matrix become 5x3.Consider we are running this matrix multiplication program for 3 processes then the matrix multiplication is performed as shown in the figure below. We can divide the work by using the for loop as shown below
    for(i = rank; i < X; i = i+size)
    matrix multiplication
    
    #include"stdio.h"
    #include"stdlib.h"
    #include"mpi.h"
    #define N 4000
    #define X 300
    #define Y 200
    int main(int argc , char **argv)
    {
     int size,rank,sum=0,i,j,k;
     int **matrix1;  //declared matrix1[X][N]
     int **matrix2; //declare matrix2[N][Y]
      int **mat_res; //resultant matrix become mat_res[X][Y]
      double t1,t2,result;
     MPI_Status status;
     
     MPI_Init(&argc, &argv);
     MPI_Comm_size(MPI_COMM_WORLD, &size);
     MPI_Comm_rank(MPI_COMM_WORLD, &rank);
     
     /*----------------------------------------------------*/
     //create array of pointers(Rows)
     matrix1 =(int **)malloc(X * sizeof(int*));
      matrix2 =(int **)malloc(N * sizeof(int*));
      mat_res=(int **)malloc(X * sizeof(int*));
     /*----------------------------------------------------*/
     
     
     /*--------------------------------------------------------------------------------*/
     //allocate memory for each Row pointer
     for(i = 0; i < X; i++)
      {
       matrix1[i]=(int *)malloc(N * sizeof(int));
       mat_res[i]=(int *)malloc(Y * sizeof(int));
      }
      
      for(i = 0; i < N; i++)
      matrix2[i]=(int *)malloc(Y*sizeof(int));
     /*--------------------------------------------------------------------------------*/
     
     for(i = 0; i < X; i++)
     {
      for(j = 0; j < N; j++)
      {
       matrix1[i][j] = 1; //initialize 1 to matrix1 for all processes
      }
     }
     
     for(i = 0; i < N; i++)
     {
      for(j = 0; j < Y; j++)
      {
       matrix2[i][j] = 2;//initialize 2 to matrix2 for all processes
      }
     }
     MPI_Barrier(MPI_COMM_WORLD);
     if(rank == 0)
     t1=MPI_Wtime();
     for(i = rank; i < X; i = i+size) //divide the task in multiple processes
     {
      for(j = 0; j < Y; j++)
      {
       sum=0;
       for(k = 0; k < N; k++)
       {
        sum = sum + matrix1[i][k] * matrix2[k][j];
       }
       mat_res[i][j] = sum;
      }
     }
     
     if(rank != 0)
     {
      for(i = rank; i < X; i = i+size)
      MPI_Send(&mat_res[i][0], Y, MPI_INT, 0, 10+i, MPI_COMM_WORLD);//send calculated rows to process with rank 0
     }
     
     if(rank == 0)
     {
      for(j = 1; j < size; j++)
      {
       for(i = j; i < X; i = i+size)
       {
        MPI_Recv(&mat_res[i][0], Y, MPI_INT, j, 10+i, MPI_COMM_WORLD, &status);//receive calculated rows from respective process
       }
      }
     }
     MPI_Barrier(MPI_COMM_WORLD);
     if(rank == 0)
     t2 = MPI_Wtime();
     result = t2 - t1;
     if(rank == 0)
     {
      for(i = 0; i < X; i++)
      {
       for(j = 0; j < Y; j++)
       {
        printf("%d\t",mat_res[i][j]); //print the result
       }
       printf("\n");
          }
     }
     if(rank == 0)
     printf("Time taken = %f seconds\n",result); //time taken
     MPI_Finalize();
     return 0;
    }
    
    
    Compile:
    mpicc matrix_mul.c -o mul  

    Execute:
    mpirun -np 2 ./mul

    Output:

    MPI Execution

    Explanation:  
            Since we are running MPI program on two cores there may be performance gain than sequential code. You can check this difference in sequential and this parallel multiplication by executing mat_mpi_mul.c and mat_seq.c programs for same large dataset(large matrices), for small dataset(matrices with few rows and column) the result for sequential may be efficient due to overhead of creating processes and message transmission.
           The table below shows the time taken by sequential and parallel matrix multiplication of 3000x4000 and 4000x2000 with different number of processes on quad core Intel i7 machine with MPICH2 library.

    Matrix Multiplication

    Read More...

    Monday, 14 October 2013

    Demonstrate Dispatcher Worker model using pthread

    Leave a Comment
            Dispatcher Worker model also called as Boss worker model. In this model there is a server process which contain one dispatcher or boss thread and multiple worker threads. Dispatcher thread continuously check the status of the worker threads and assign job to the thread which is free or idle. Working of this model can be shown in the figure shown below.
    Dispatcher Worker Model

            Here, we are going to demonstrate the working of dispatcher worker model in pthread which is also called as posix thread. As shown in the figure above we are going to create 4 worker threads using pthread_create function and 1 main thread is going to act as dispatcher thread which assigns the job. In the pthread example explain below we are going to consider that there are three jobs with name job1(), job2() and job3(), which are working for 40 seconds which is sufficient time for user to assign job to other threads while one or two are threads are working which is helpful for testing purpose, here you can add your own code. Here we are assigning job when main thread gives signal to worker threads this can be done using pthread_cond_wait() and pthread_cond_signal() functions for details you can visit here.
           As explain above, example of pthread program dispatcher_worker.c is shown below.
    You can compile this program using command below
    gcc dispatcher_worker.c -lpthread
    You can run this program using command below
    ./a.out

    #include"stdio.h"
    #include
    #include
    #include 
    pthread_t th1, th2, th3, th4;
    pthread_cond_t con0 = PTHREAD_COND_INITIALIZER;
    pthread_cond_t con1 = PTHREAD_COND_INITIALIZER;
    pthread_cond_t con2 = PTHREAD_COND_INITIALIZER;
    pthread_cond_t con3 = PTHREAD_COND_INITIALIZER;
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
    pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER;
    pthread_mutex_t mutex4 = PTHREAD_MUTEX_INITIALIZER;
    int jobs[4];   //shared array used to submit job
    void *fun1 (void *);
    void *fun2 (void *);
    void *fun3 (void *);
    
    int job1 (int x)
    {
     printf ("This is job1 from thread %d\n", x);
     sleep (40);   //working for 10 seconds 
     //(Suffient time to submit jobs to other threads for testing purpose)
     return 0;
    }
    
    int job2 (int x)
    {
     printf ("This is job2 from thread %d\n", x);
     sleep (40);   //working for 10 seconds 
     //(Suffient time to submit jobs to other threads for testing purpose)
     return 0;
    }
    
    int job3 (int x)
    {
     printf ("This is job3 from thread %d\n", x);
     sleep (40);   //working for 10 seconds 
     //(Suffient time to submit jobs to other threads for testing purpose)
     return 0;
    }
    
    void * fun0 (void *arg)
    {
     int busy = 0;
     int j = 1;
     pthread_mutex_lock (&mutex);
     while (1)
     {
      pthread_cond_wait (&con0, &mutex); //waiting for job to be submitted
      if (jobs[0] == 1)
      {
       job1 (busy);
       jobs[0] = 0;
      }
      else if (jobs[0] == 2)
      {
       job2 (busy);
       jobs[0] = 0;
      }
      else if (jobs[0] == 3)
      {
       job3 (busy);
       jobs[0] = 0;
      }
      else
      {   //do nothing
      }
     }
     pthread_mutex_unlock (&mutex);
    }
    
    void * fun1 (void *arg)
    {
     int busy = 1;
     pthread_mutex_lock (&mutex2);
     while (1)
     {
      pthread_cond_wait (&con1, &mutex2); //waiting for job to be submitted
      if (jobs[1] == 1)
      {
       job1 (busy);  //pass the thread number
       jobs[1] = 0;
      }
      else if (jobs[1] == 2)
      {
       job2 (busy);
       jobs[1] = 0;
      }
      else if (jobs[1] == 3)
      {
       job3 (busy);
       jobs[1] = 0;
      }
      else
      {   //do nothing
      }
     }
     pthread_mutex_unlock (&mutex2);
    }
    
    void *
    fun2 (void *arg)
    {
     int busy = 2;
     pthread_mutex_lock (&mutex3);
     while (1)   //going to infinite state 
     {
      pthread_cond_wait (&con2, &mutex3); //waiting for job to be submitted
      if (jobs[2] == 1)
      {
       job1 (busy);
       jobs[2] = 0;
      }
      else if (jobs[2] == 2)
      {
       job2 (busy);
       jobs[2] = 0;
      }
      else if (jobs[2] == 3)
      {
       job3 (busy);
       jobs[2] = 0;
      }
      else
      {   //do nothing
      }
     }
     pthread_mutex_unlock (&mutex3);
    }
    
    void * fun3 (void *arg)
    {
     int busy = 3;
     pthread_mutex_lock (&mutex4);
     while (1)
     {
      pthread_cond_wait (&con3, &mutex4); //waiting for job to be submitted
      if (jobs[3] == 1)
      {
       job1 (busy);
       jobs[3] = 0;
      }
      else if (jobs[3] == 2)
      {
       job2 (busy);
       jobs[3] = 0;
      }
      else if (jobs[3] == 3)
      {
       job3 (busy);
       jobs[3] = 0;
      }
      else
      {   //do nothing
      }
     }
     pthread_mutex_unlock (&mutex4);
    }
    
    int main ()
    {
     int i, j, k = 0, job_no = 0, th_no = 0;
     char choice, cond_var[20];
     for (i = 0; i < 4; i++)
     jobs[i] = 0;
     pthread_create (&th1, NULL, fun0, NULL);
     pthread_create (&th2, NULL, fun1, NULL);
     pthread_create (&th3, NULL, fun2, NULL);
     pthread_create (&th4, NULL, fun3, NULL);
     while (1)
     {
      k = 0;
      //printf ("Assign job to the free threads given below\n");
      for (i = 0; i < 4; i++)
      {
       if (jobs[i] == 0)
       {
        printf ("%d\t", i);
        k++;
       }
      }
    
      if (k > 0)
      {
       printf("numbered threads are free\n");
       printf("-------------------------------------------------------");
       printf ("\nWant to give job Y:yes N:no T:\"Terminate\" \n");
       scanf ("%s", &choice);
       if (choice == 'Y' || choice == 'y')
       {
        printf ("Enter job number (1-3) and thread number (0-3)\n");
        scanf ("%d %d", &job_no, &th_no);
        if (th_no == 0)
        {
         pthread_mutex_lock (&mutex);
         jobs[th_no] = job_no;
         pthread_cond_signal (&con0); //wake up thread waiting for condition variable con0
         pthread_mutex_unlock (&mutex);
        }
        else if (th_no == 1)
        {
         pthread_mutex_lock (&mutex2);
         jobs[th_no] = job_no;
         pthread_cond_signal (&con1); //wake up thread waiting for condition variable con1
         pthread_mutex_unlock (&mutex2);
        }
        else if (th_no == 2)
        {
         pthread_mutex_lock (&mutex3);
         jobs[th_no] = job_no;
         pthread_cond_signal (&con2); //wake up thread waiting for condition variable con2
         pthread_mutex_unlock (&mutex3);
        }
        else if (th_no == 3)
        {
         pthread_mutex_lock (&mutex4);
         jobs[th_no] = job_no;
         pthread_cond_signal (&con3); //wake up thread waiting for condition variable con3
         pthread_mutex_unlock (&mutex4);
        }
        else
        {
        }
       }
       else if (choice == 'T' || choice == 't')
       {
        exit (0);
       }
       else
       {
       }
      }
      else if (k == 0)
      {
       printf ("All threads are busy\n");
       sleep (2);
      }
      else
      {   //do nothing
      }
     }
    
     pthread_join (th1, NULL);
     pthread_join (th2, NULL);
     pthread_join (th3, NULL);
     pthread_join (th4, NULL);
     return 0;
    }
    
    Output:

          Since multiple threads are running parallel the sequence of output (that is printing) of statements may get vary. As shown in the figure above line number 12 is the output of previously given job to thread number 0, but output of this statement is appearing after line number 11 which is the output line of main thread. So you the program is waiting for input at line number 13 not at 12.
    Read More...

    Friday, 11 October 2013

    Apache Thrift Tutorial

    1 comment

    Introduction

           Apache thrift is a tool developed at Facebook which is used for automatically creating remote servers in Remote Procedure Call (RPC) in different languages. Thrift means economical, since it is saving time and cost for creating remote servers in RPC.  Apache thrift support many different languages . Apache thrift won't create client, you require to create the client program manually. Apache thrift is an Interface Definition language (IDL) used to create services in a different language.

    Installation 

    On Ubuntu:
           You can install all dependencies by giving only one single command as shown below
    sudo apt-get install libboost-dev libboost-test-dev libboost-program-options-dev libevent-dev automake libtool flex bison pkg-config g++ libssl-dev 

    OR

           If there is an error in above command please check due to which dependency error is occurring.
    • First check whether your g++ version is greater or equal to 4.2 you may check the version with the command given below
      g++ --version   (This should be >= 4.2)
    • Install lex and yacc using command given below
      sudo apt-get install byacc flex
    • Install boost library using command given below
      sudo apt-get install libboost-all-dev
    • Install autoconf which is require for building the source
      sudo apt-get install autoconf
    • Install  automake
      sudo apt-get install automake
    • Install libtool
      sudo apt-get install libtool
    • install libssl-dev
       sudo apt-get install libssl-dev
    • Install pkg-config
      sudo apt-get install pkg-config
    • Install libevent-dev
      sudo apt-get install libevent-dev
    • Install bison
      sudo apt-get install bison

           Now download the apache thrift and extract it. After extracting open terminal and go to the path where thrift is extracted and give the following commands
    ./configure
    make
    sudo make install
           You can check whether apache thrift is installed properly or not by giving command below. If you are able to see the version of thrift then your installation is completed successful.
    thrift --version

    Use

          As explain before we can create source codes for many languages without installation of that language, but to run created source code you will require to install those language. To create remote server you will require to create a file with extension thrift. This thrift file contain thrift interface description language we will explain this in short for detail refer link.

    Lets create one example which performs basic arithmetic operations Thrift_IDL.thrift.

    #this is comment
    #!/usr/local/bin/thrift --gen cpp
    
    namespace cpp Test #this indicates that given thrift is applicable to cpp 
    
    service arithmetic_op  #create class arithmetic_opHandler : virtual public arithmetic_opIf with following public function
    {       
      i32 add(1:i32 num1, 2:i32 num2),  #this create function with int32_t add(const int32_t num1, const int32_t num2)
      i32 sub(1:i32 num1, 2:i32 num2),  #this create function with int32_t sub(const int32_t num1, const int32_t num2) 
      i32 mul(1:i32 num1, 2:i32 num2),  #this create function with int32_t mul(const int32_t num1, const int32_t num2) 
      i32 div(1:i32 num1, 2:i32 num2),  #this create function with int32_t div(const int32_t num1, const int32_t num2)
    }
    
    service arithmetic_Demo      #this is second service for dispay
    {
    i32 display(1:i32 num1, 2:i32 num2)
    }
    To generate server for this file you require to give the command
    thrift --gen cpp Thrift_IDL.thrift
           This command will generate one folder with name "gen-cpp" which contain 10 files as shown in the figure below. This number of file and the format of files changes as the language changes, here we are considering the files for cpp.
    Apache Thrift
      
           Since we don't define any struct or enum declared in thrift file, the file Thrift_IDL_types.h, Thrift_IDL_types.cpp are only initialized but not used.

    Modify Functions declared in Services(.thrift file):
           Functions declared in the services of thrift file are only initialized by thrift. You require to add the contain to perform some action you require.
           We will take example of arithmetic_op service: thrift will create arithmetic_op_server.skeleton.cpp file which contain main function and thrift will create arithmetic_opHandler class which contain constructor and the number of functions declared in the thrift file as shown below.
    class arithmetic_opHandler : virtual public arithmetic_opIf {
     public:
      arithmetic_opHandler() {
        // Your initialization goes here
      }
    
      int32_t add(const int32_t num1, const int32_t num2) {
        // Your implementation goes here
        printf("add\n");
      }
    
      int32_t sub(const int32_t num1, const int32_t num2) {
        // Your implementation goes here
        printf("sub\n");
      }
    
      int32_t mul(const int32_t num1, const int32_t num2) {
        // Your implementation goes here
        printf("mul\n");
      }
    
      int32_t div(const int32_t num1, const int32_t num2) {
        // Your implementation goes here
        printf("div\n");
      }
    };
    
            You can add logic of addition, subtraction, multiplication and division in the functions add(), sub(), mul(), div() respectively. This functions are taking two inputs from client and printing the function name, instead of this you can add the logic of arithmetic operation.
    Compiling:
    • g++ -I/usr/local/include/thrift -c arithmetic_Demo.cpp
    • g++ -I/usr/local/include/thrift -c arithmetic_Demo_server.skeleton.cpp
    • g++ -I/usr/local/include/thrift -c arithmetic_op.cpp
    • g++ -I/usr/local/include/thrift -c arithmetic_op_server.skeleton.cpp
    • g++ -I/usr/local/include/thrift -c Thrift_IDL_constants.cpp
    • g++ -I/usr/local/include/thrift -c Thrift_IDL_types.cpp
    To compile all files in one stroke you can use the command given below
    g++ -I/usr/local/include/thrift -c *.cpp
    Here *cpp represent all files with extension .cpp.
    Explanation:
          -I: option which is used by gcc compiler to locate the header files. In this compilation we are suggesting the gcc compiler to search for the header files in the "/usr/local/include/thrift/" folder also.
          Since it is only compilation gcc compiler won't link the thrift libraries which eliminates the requirement of including thrift library with -lthrift.
          -c: option in gcc compiler is used to create object files if you don't provide -o followed by your custom name of object file it will create object file with the same name of your c or cpp file with .o extension.

    Linking:
           Since there are two services in our example we get two Service_name_server_skeleton.cpp files which contain main function in it. Due to this we require to link this two service_skeleton.cpp files separately, which will create two executables with two different service.
           You can use the command given below for linking the services

    Link "arithmetic_op" service:
     
    g++ -L/usr/local/lib/ arithmetic_op.o arithmetic_op_server.skeleton.o Thrift_IDL_constants.o Thrift_IDL_types.o -lthrift -o arithmetic_op

    Link "arithmetic_Demo" service:

    g++ -L/usr/local/lib/ arithmetic_Demo.o arithmetic_Demo_server.skeleton.o Thrift_IDL_constants.o Thrift_IDL_types.o -lthrift -o arithmetic_Demo

    Explanation:
    -L: This option is used when you want compiler to link with libraries present in directory other than LD_LIBRARY_PATH environment variable. Here we have used to link with thrift library named "libthrift.a" or "libthrift.so". Here .a represent static library where as .so represent dynamic library.

    -o: This option is used to give custom name to your executable by default it is a.out
    Read More...

    Monday, 30 September 2013

    Indent your C code within second

    1 comment
    GNU
        Indenting huge C program manually is difficult and time consuming. To reduce this effort we can use "GNU indent" tool. We can indent C program automatically with this tool. This tool is only design to indent C programs and not for C++.

    Installation

        For  Debian OS(Ubuntu, OpenSuse) we can install using command given below.
    sudo apt-get install indent
        For Redhat based OS(like Fedora, CentOS) we can install using command given below.
    yum install indent
    OR
        You can also download tar.gz and install manually using 
    ./configure
    make
    make install   (give command with root/sudoer privileges)

    Uses

        As stated previously we can use this tool to automatically indent any C program.
    Syntax:
    indent prog1.c prog2.c
        This command will indent both the programs, if you want to save the files with different name to access the older files you can use the following syntax or command
    indent prog1.c -o prog1_indent.c
        In this you can indent only one file at a time.
    Below example shows the unintended C code(uint.c)
    
             #include"stdio.h"
       #include"stdlib.h"
          int main()
        {
         printf("This is unintended code")  ;
             return 0;
      }
    
    
    After using intend command you get the intended code as shown below
    intend unin.c
    
    #include"stdio.h"
    #include"stdlib.h"
    int
    main ()
    {
      printf ("This is unintended code");
      return 0;
    }
    
    
    There are three by default styles of indenting the C program 
    1. gnu-style (it is by default)
    2. k-and-r-style (Kernighan & Ritchie style)
    3. linux-style
        For 2nd & 3rd style you have to specify it explicitly after as shown below
    indent --linux-style  prog1.c
    indent --k-and-r-style  prog1.c
        There are many options available to customize the above three styles out of which important option are given below you can find detail in the user manual  of indent.
    -nsaf  => --no-space-after-for
    -nsai  => --no-space-after-if
    -nsaw => --no-space-after-while
    -sob   => --swallow-optional-blank-lines (delete the extra blank lines)
    -tsn    => --tab-sizen (we can set the tab size by changing the n)
    (n is the length of the tab)
    -nut   => --no-tabs (Use spaces instead of tabs)

        In some programs there are many "carriage return" (\r) characters are present indent tool will replace this "carriage return" to the "new line" (\n) which will cause unnecessary blank lines.
        To remove this unwanted "carriage return" (\r) from program we can use following command
    cat prog1.c | tr -d "\r" >prog1.c
        In this command tr is used to translate or delete the characters.
    After removing this "carriage return" you can use indent command to get proper output.



     





    Read More...

    Thursday, 26 September 2013

    Pthread_cond_wait & Pthread_cond_signal simple example

    3 comments
    pthread_cond_t
    pthread_cond_t is a condition variable which can be used by thread_cond_wait(), pthread_cond_signal(), pthread_cond_broadcast() and thread_cond_timedwait().

    pthread_cond_wait() :
    • This routine stops the execution of the calling thread and wait for appropriate signal to start the thread execution.
    • pthread_cond_wait() must be called after pthread_mutex_lock() and before pthread_mutex_unlock().
    • pthread_cond_wait() release the mutex lock while it is waiting, so that pthread_cond_signal(), which is also called in the mutex should get access and can give signal to waiting thread to awake.
    Syntax: pthread_cond_wait(pthread_cond_t *condition, pthread_mutex_t *mutex)

    pthread_cond_signal() 
    • This routine is used to wakeup the thread which is waiting for any condition to occur.
    • If in any case pthread_cond_signal() calls first before the execution of pthread_cond_wait() then it cannot awake the thread which is waiting for the condition to occur and your thread calling pthread_cond_wait() will go to the infinite waiting state or can be called as deadlock state.
    • Your pthread_cond_signal() should be called at least once for corresponding pthread_cond_wait() function call.
    Syntax: pthread_cond_signal(pthread_cond_t *condition)
    This signal will wakeup the pthread_cond_wait() with condition variable condition.
    The program given below will explain this routines signal_wait.c

    
    #include "pthread.h"
    #include "stdio.h"
    #include"unistd.h"
     
    volatile int sv=10;
    volatile int x,y,temp=10;
    pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t con=PTHREAD_COND_INITIALIZER;
    pthread_t child1,child2,child3;
    int condition=1,val=1;
    int count=1;
     
    void *ChildThread1(void *arg)
    {
        sleep(1);
        pthread_mutex_lock (&mut);
            printf("wait called\n");
            while(count<10)                      //if while loop with signal complete first don't wait
            {
                printf("In wait\n");
                pthread_cond_wait(&con, &mut);  //wait for the signal with con as condition variable
            }
            x=sv;
            x++;
            sv=x;
            printf("The child1 sv is %d\n",sv);
        pthread_mutex_unlock (&mut);
    }
     
    void *ChildThread2(void *arg)
    {
     
        while(count<10)
        {
            pthread_mutex_lock (&mut);
                pthread_cond_signal(&con);  //wake up waiting thread with condition variable
                                            //con if it is called before this function
                if(val==1)
                {
                    y=sv;
                    y--;
                    sv=y;
                    printf("The child2 sv is %d\n",sv);
                    val++;
                }
                count++;
            pthread_mutex_unlock (&mut);
             
        }
        printf("mutex released\n");
        printf("chil2 exit\n");
    }
     
    int main(void)
    {
        int co=1;
        pthread_create(&child1,NULL,ChildThread1,NULL);
        pthread_create(&child2,NULL,ChildThread2,NULL);
        pthread_join(child1,NULL);
        pthread_join(child2,NULL);
     
        pthread_cond_destroy(&con);
        pthread_mutex_destroy(&mut);
        pthread_exit(NULL);
        return 0;
    }
    
    
    Read More...

    Monday, 23 September 2013

    Windows setup cannot configure Windows to run on this hardware

    Leave a Comment
         While installation of Windows some times after restarting Windows on last step "completing installation" this error comes and your installation never completes.
         To install Windows properly in such cases you can follow the steps given below

    1. Reset your BIOS to all default values and restart. Changes in BIOS may be the cause of this error.
    2. After restarting if the problem remains same then follow the steps below.
    3. Once again boot from your bootable CD/DVD or bootable pendrive.
    4. Don't delete/format the windows partition where you have installed your Windows 7.
    5. Select the same partition where you have installed your Windows previously and which is giving the error "Windows setup cannot configure windows while to run on this hardware" and install Windows on this drive once again.
    6. This will give you warning as shown in the figure given below, click on ok button and your installation start.
      Windows.old
    7. Now all your data of previous windows will get store on windows.old folder on the drive where you have installed the windows.
    8. You can delete this partition and make free space on the drive.
    Read More...

    Friday, 20 September 2013

    Minimizing the Finite Automata using c

    Leave a Comment
    In this given example we have find out the minimization of finite automata with single final state given in the figure below
    Finite Automata
    We can store this FA in a matrix of 2x7 where row represent the input and column represent the states mapped to array_index+1.
    State pair can be shown using lower triangular matrix of (number_of_states - 1) x (number_of_states - 1) array as shown in the figure below which can be used to check the equivalent states.
    State Pair
     After Minimization the minimized finite automata looks as shown in the figure given below.
    Minimization of FA
    Download Source code for c program to minimize the Finite Automata here minimizeFA.c

    
    #include"stdio.h"
    #define states 7  //number of states
    
    int
    main ()
    {
      int s1, s2, temp1, temp2, temp3, temp4, i = 0, j =
        0, state_pair[states - 1][states - 1], f, k, flag = 1;
      int FA[2][states] = { 2, 4, 6, 4, 6, 4, 6, 3, 5, 7, 5, 7, 5, 7 }; //input your state transsion diagram 
      int xtemp[20], it = 0;
      int x[states], l = 0;
      int count = 0, arr1[20], arr2[20], c = 0;
      int temp[states];
      for(i = 0; i < states; i++)
        {
          temp[i] = 0;
        }
      for(i = 0; i < states; i++)
        {
          x[i] = 0;
        }
      //This is Finite automata for {0,1}*{10}
      printf ("\nArray elements are");
    
      for(i = 0; i < 2; i++)
        {
          printf ("\n");
          for(j = 0; j < states; j++)
     {
       printf ("\t%d", FA[i][j]);
     }
        }
    
      for(i = 0; i < (states - 1); i++)
        {
          for(j = 0; j < states - 1; j++)
     state_pair[i][j] = 0;
        }
    
      printf ("\nEnter final state");
      scanf ("%d", &f);
      i = f - 2;
      j = f - 1;
    
      for(k = 0; k <= f - 2; k++)
        state_pair[i][k] = 1;
    
      for(k = 0; k < (states - 1); k++)
        {
          if(k <= f - 2)
         {
         }
          else
     state_pair[k][i + 1] = 1;
        }
    
      while(flag)
        {
          flag = 0;
    
          for(i = 0; i < (states - 1); i++)
     {
       for(j = 0; j < (states - 1); j++)
         {
           s1 = i + 2;
           s2 = j + 1;
    
           if(s1 > s2)
      {
        if(state_pair[i][j] != 1)
          {
            temp1 = FA[0][s1 - 1];
            temp2 = FA[0][s2 - 1];
            temp3 = FA[1][s1 - 1];
            temp4 = FA[1][s2 - 1];
    
            //      printf("S1 %d  S2 %d\n",s1,s2);
            //      printf("d(%d,0)=%d \t d(%d,0) %d\n",s1,temp1,s2,temp2);  
            //      printf("d(%d,1)=%d \t d(%d,1) %d\n\n",s1,temp3,s2,temp4);
    
            if(temp1 != temp2) //check whether state p!=q for 0 input
       {
         if(state_pair[temp1 - 2][temp2 - 1] == 1
            || state_pair[temp2 - 2][temp1 - 1] == 1)
           {
             state_pair[i][j] = 1;
             flag = 1;
           }
       }
    
            if(temp3 != temp4) //check whether state p!=q for 1 input
       {
         if(state_pair[temp3 - 2][temp4 - 1] == 1
            || state_pair[temp4 - 2][temp3 - 1] == 1)
           {
             state_pair[i][j] = 1;
             flag = 1;
           }
       }
          }
      }
         }
     }
        }
    
      printf ("\nSecond array");
    
      for(i = 0; i < (states - 1); i++)
        {
          printf ("\n %d", i + 2);
    
          for(j = 0; j < (states - 1); j++)
     {
       if(i >= j)
         {
           printf ("\t%d", state_pair[i][j]);
           if(state_pair[i][j] == 0)
      {
        arr1[count] = i + 2;
        arr2[count] = j + 1;
        count++;
      }
         }
     }
        }
    
      printf ("\n\n");
    
      for(i = 0; i < (states - 1); i++)
        printf ("\t%d", i + 1);
      printf ("\n");
    
      c = 0;
      i = 0;
      printf ("\n\n");
    //code to check the same states(from unmark) start here
      while(1)
        {
          if(x[arr1[c] - 1] == 0 && x[arr2[c] - 1] == 0)
     {
       x[arr1[c] - 1] = 1;
       x[arr2[c] - 1] = 1;
       xtemp[it] = arr1[c];
       it = it + 1;
       xtemp[it] = arr2[c];
       it = it + 1;
       for(l = 0; l < count; l++)
         {
           if(x[arr1[l] - 1] == 0 && x[arr2[l] - 1] == 1)
      {
        x[arr1[l] - 1] = 1;
        xtemp[it] = arr1[l];
        it = it + 1;
      }
           if(x[arr1[l] - 1] == 1 && x[arr2[l] - 1] == 0)
      {
        x[arr2[l] - 1] = 1;
        xtemp[it] = arr2[l];
        it = it + 1;
      }
         }
       printf("..............following states are in same group...............\n");
       for(i = 0; i < it; i++)
         printf ("%d\t", xtemp[i]);
       it = 0;
     }
          printf ("\n");
          c++;
          if(c == count)
     break;
        }
      return 0;
    }
    
    
    
    Read More...

    Friday, 13 September 2013

    Pass multiple arguments in pthread_create

    Leave a Comment
    Pthreads

            Posix thread normally known as pthread. It is an API to create threads on Unix like operating system such as GNU/Linux, MAC etc. Windows doesn't provide support for this API. In Windows some third party softwares are available which can be used for writing multithread application using pthread, pthreads-w32 is one of this.
            To create thread pthread uses pthread_create function with syntax given below.

    int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
            This function creates a new thread and that thread will execute the function specified as third parameter with arguments specified in fourth parameter. There is no provision to transfer more than one argument to the function which is called by pthread_create.
            If you want to transfer multiple arguments then you require to create a structure with arguments you require to pass to the function and then by transferring this structure you can pass as many arguments as you want to transfer. The program pthread.c below is one such example of passing multiple parameters

    
    #include"pthread.h"
    #include"stdlib.h"
    #include"stdio.h"
    
    struct test
    {
     int var1,var2;
     float var3;
    };
    
    typedef struct test struct1;
    
    void* fun1(void* a)
    {
     struct1 *b;
     b=(struct1*)a;
     b->var3=b->var1+b->var2;
     printf("\nOperation successful the sum is %f\n",b->var3);
    }
    
    int main()
    {
     pthread_t th1,th2;
     struct1 *a;
     a=(struct1 *)malloc(sizeof(struct1));
     a->var1=10;
     a->var2=20;
     pthread_create(&th1,NULL,fun1,(void*) a);
     pthread_join(th1,NULL);
     return 0;
    }
    
    

    Read More...

    Friday, 6 September 2013

    Strace : Moniter system calls

    Leave a Comment

    Introduction

    Strace is a small useful debugging tool which traces all the system calls and signals used by  the program. Internally Strace uses ptrace system call to trace the system calls executed by the program. This list of system calls is useful to get clear idea, how program is interacting with the kernel.

    Installation:

    In Ubuntu you can install Strace using 
    sudo apt-get install strace
    In CentOS you can install by
    yum install strace

    OR 
    Download the Strace-4.8.tar.xz
    tar xvJf strace-4.8.tar.xz
    cd strace-4.8/
    ./configure
    make
    make install        (as root or sudoer user)

    Use: 

    1. strace who        (Default it will print all the system call and signals)
      execve("/usr/bin/who", ["who"], [/* 42 vars */]) = 0
      brk(0)                                 = 0x1568000
      access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
      mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2e366b1000
      access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
      open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
      ..
      ..
    2. strace -o output.txt who (-o is used to write the result of strace utility in the file)
      strace who > output.txt
      This will write the result of executing command here it is who, in the output.txt file not the system calls that are traced by the strace command.
    3. strace -c who (-c is used to calculate total number of times the system call is appeared without giving the details of each system call)
    4. strace -C who (-C is used to calculate total number of times the system call is appeared with giving the details of each system call)
    5. strace -e write who (-e option is used to detect specific system calls provided out of all)
      write(1, "krishna  tty7         2013-09-06"..., 44krishna  tty7         2013-09-06 09:36 (:0)
      ) = 44
      write(1, "krishna  pts/0        2013-09-06"..., 46krishna  pts/0        2013-09-06 12:47 (:0.0)
      ) = 46
      write(1, "krishna  pts/1        2013-09-06"..., 46krishna  pts/1        2013-09-06 11:54 (:0.0)
      ) = 46
      +++ exited with 0 +++

      strace -e trace=read,write who (We can use this command to detect multiple system calls as we have perform above example for only one)
    6. We can also get the traces of currently running (executing) process
      strace -p 2700 (here 2700 is the process id of the currently running job)
    Read More...

    Sunday, 21 July 2013

    Disable usb drives in Windows and Linux

    Leave a Comment
    There are many reasons due to which you may want to disable the USB drive such as virus attacks in windows, in exam to stop students from using USB drives. We can use following method to stop users other than administrator from using USB drive.

    Disable USB Drive in Window

    Step 1:  click Start->Run
    Step 2:  in Run windows type regedit. Regedit is a graphical view for all configuration information about the inbuilt and installed software in windows.

    Step 3: In regedit select the path as   HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR


    Step 4: In this select the Start file after this select Hexadecimal base, by default it is blank now enter 4 in the value data field and click OK and close regedit and your USB drives gets disabled. If you want to enable USB drive again then open this file, delete the value and keep it blank.


    Disable USB Drives in Linux

    Step 1: First check the kernel release of your current kernel OS because one operating system may have many versions of kernel. When we update Linux it keeps older version of kernel we can find current kernel version using uname -r command use  
    kernel_version=$(uname -r) 
    command so that you can use kernel_version variable for our next purpose.

    Step 2: Enter following command using root privileges
    mv /lib/modules/kernel_version/kernel/drivers/usb/storage
    /lib/modules/Kernel_version/kernel/drivers/usb/storage_old
    this command is used to change the name of storage directory to storage_old which disable the USB drive. If you want to access the USB drive again, change the name of this storage_old directory to storage again using root privileges.
    Read More...

    Tuesday, 16 July 2013

    Windows keep restarting

    1 comment

    This problem may occur due to different reasons such as corrupted boot sector, viruses. In my opinion there are two solutions to solve this problem

    1. Using recovery console

    Follow the steps given below but beware that after using this commands your other OS like CentOS, Ubuntu will be removed from the grub. Do to which you will not able to use your other OS installed with Windows.
    • boot your machine from windows bootable DVD or USB.
    • go to recovery console 
    • type the following commands 
      • bootrec.exe/rebuildbcd     (scan all disks which contain Windows installation)
      • bootrec.exe/fixmbr           (write new MBR)
      • bootrec.exe/fixboot          (Write new boot sector)
    • This commands search for windows installed drive and add those entries to grub.
    • After this shutdown the machine and start it.

    2. Installing Ubuntu alongside windows

    This is safer option than first one because this method keeps both the Windows,  Other Linux, and this new Ubuntu which you are going to install alongside windows. After installing Ubuntu all the grub entries go the Ubuntu, due to which problem get solved. By using this method you will be able to use two flavors of Linux (Ubuntu:-debian based + CentOS:- Redhat based + Windows) with Windows. This method require free disk space (minimum requirement of Ubuntu)on C drive (where your Windows is installed) to install Ubuntu alongside Windows.
    By using this method we can also get CentOS back after removal of its entry from grub due to some problem and going to grub rescue.
    Read More...

    Tuesday, 11 June 2013

    No valid sudoers sources found quitting ubuntu

    1 comment
    This error happen due to change in permission of sudoers file.
    Pkexec command is used to execute command as another user. Older versions of Ubuntu don't support this command. If you are able to use pkexec command then you are not require to reboot and go to recovery mode use following commands

    pkexec chown -R root:root /etc/sudoers.d
    pkexec chmod u=rwx,g=rx,o=rx /etc/sudoers.d/
    pkexec chmod u=r,g=r,o= /etc/sudoers.d/*


    If you are running on old versions which could not support pkexec then you require to use recovery mode.
    You can go into recovery mode by selecting grub menu ending with recovery mode option ->root -> give root password
    after this enter command

    fdisk -l (gives all detail disk partition)

    Since in ubuntu recovery mode is read only you will require to remount in read-write mode using following command

    mount -o remount,rw /dev/sda(drive containing installation i.e root)
    now enter above commands without pkexec as below

    chown -R root:root /etc/sudoers.d
    chmod u=rwx,g=rx,o=rx /etc/sudoers.d/
    chmod u=r,g=r,o= /etc/sudoers.d/*


    now reboot and you will be able to use sudo or su command

    Read More...

    Sunday, 26 May 2013

    passwd command not working in single user mode

    Leave a Comment
    If your passwd command is not working in single user mode and you want access of machine then first remove the password of root or any user already present as explained below. After removing password, login to that user without password and change password for the user by using passwd command.
    You can remove the password by editing shadow file present in /etc/ folder with file name shadow
    Shadow file format is as below
    root:$1$CQoPk7Zh$370xDLmeGD9m4aF/ciIlC.:14425:0:99999:7:::

    There are 6 fields separated by ':'. To remove password delete second field present in line with first field showing user name it should look like
    root::14425:0:99999:7:::

    This file is read only so after changing file you require to give command as wq! to save changes in vi editor (since in single user mode other editors won't work) this will change your file. If this is not working then you have to change the permissions of the shadow file. To change permission use chmod 777 shadow command.

    Check the file is changed, if it is changed then you can restart by command reboot.



    Read More...

    Friday, 3 May 2013

    Secure CoPy (SCP)- Secure Option to Copy Files in Linux

    8 comments

     

    1. What is Secure CoPy (SCP) ?

                SCP is a command used to transfer files or folders securely to a particular remote user. In windows sharing of folders or files can be done in LAN only. There is no facility provided to transfer data securely from one user to another remote user, we require to use service from some third party software to do so. In Windows you can get this facility by installing WinSCP software and transfer the files directly to the Linux OR you can install OpenSSH on Windows machine using cygwin which is a collection of tools which provide a Linux like environment for Windows operating system. After OpenSSH installation you can transfer files using SCP from Windows to Linux and from Linux to Windows.

    2. How to Use SCP ?

               To use SCP, first you have to start ssh service on the other side where you want to transfer the data. To start the service in red hat based OS switch to root user and give the command as " service sshd start ", for debian based OS you can use " sudo /etc/init.d/ssh start " or " sudo service ssh start ". SCP requires password of the remote machine to copy files or folder, so you can keep ssh server running all time, no one can copy irrelevant material without prior authentication.
              After starting the ssh service of target system you can give following command to start copy.
    Syntax to copy single file:
             scp file1.txt user@target_IP_Address:~/Destination_PATH 

    Here, you require to provide user name with IP address of remote system as shown above. 
    Here ~ is used to represent home directory of a particular user in Linux.
    After entering this command you need to provide the password of the target system , if password is correct then your copying files get started.
    To copy multiple files using SCP, you can give multiple file names separated by space. Files may have different extensions.

    Syntax to copy multiple files:
              scp file.txt file2.avi file3.iso user@target_IP_Address:~/Desktop

    To copy particular folder you can use SCP command with " -r " option which indicates recursive operation.

    Syntax to copy single folder:
              scp -r folder_name user@target_IP_Address:~/Desktop


    You can also copy multiple folders using SCP like we did with multiple files as given above. You can use following command to copy multiple folders using SCP command.

    Syntax to copy multiple folders:
             scp -r folder1 folder2 user@target_IP_Address:~/Desktop 


    3. Errors and solutions

    • One common error is " port 22: Connection refused " which occurs when ssh service of the destination machine is stopped. You can eliminate  this error by starting ssh service at the destination machine.
    • Another error is that your file or folder get copied to your own directory with user name followed with IP address like " user@target_IP_Address ". This error happens if " :PATH " is not mentioned in command.
    Read More...

    Tuesday, 30 April 2013

    What is ssh ?

    Leave a Comment

    1. What is Secure SHell (SSH)

       SSH is a network protocol which uses public-key cryptography. SSH is more secure than rsh, telnet. Generally SSH is used to access remote machine using password authentication and to form cluster of different machines. You can also see GUI for file manager of remote system so that controlling becomes easier (nautilus for GNOME, krusader for KDE etc.). Generally in Linux, openssh provides SSH protocol. You can use PUTTY to act as SSH client for Windows OS. To install SSH server in windows you have to install CYGWIN. In Windows you can not get GUI through file manager as you do in Linux.
       CYGWIN is a collection of tools which provide a Linux-like environment for Windows operating system.

    2. Installation

    • Many Linux OS images comes with this two required packages, openssh client and server already installed on it, but there are some basic images with around 700 MB which won't contain these packages.
    • To know whether you have SSH installed or not you can use the command  " which ssh " if it doesn't give any output then you will have to install it.
    •  To install SSH in CentOS use " yum install openssh* ". This command will install openssh-client and openssh-server for you.
    • To install SSH in Ubuntu use " sudo apt-get install ssh ".
    • To install CYGWIN in Windows please refer this video.

    3. Uses

    • Machine with SSH client installed acts as client that can access other machine installed with SSH server.
    • Machine with SSH server installed acts as server and receives multiple request from SSH client.
    • SSH can be used to create cluster of different machines to run any job on cluster using password-less SSH login.
    •  After installing SSH client, you get Secure CoPy (SCP) facility which is  used to copy files to remote host.
    To log in remote machine, enter following command

    ssh -X user@IP_ADDRESS_OF_REMOTE_SYSTEM

    In this command, use of -X Enables X11 forwarding. By using X11 forwarding, we can access GUI using file manager, else you will not be able to access GUI. Be aware of capital X, because small x stands for disable X11 forwarding which won't show you GUI.

    4. Errors and Solutions

    • If you are unable to get access into server system, then check the user account name. That user account must be present at server side, because ssh won't give any error even if user account is not present on server side.
    •  " port 22: No route to host " this error occurs when wrong IP address which is not present is entered.
    • One common error is " port 22: Connection refused " this error occur if ssh service at remote system is stopped. You can overcome this by starting ssh service on the remote machine.
    •  Error " WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! " " IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! "
            Cause :-  This error occurs due to change of OS at the server side or if other illegal person is using your requested server IP whose public key is known to you. Public key is stored in " known_hosts " file present in " /home/user/.ssh/ "  directory at first time when you login to server or remote machine.
            Solution :- If you want to access other machine which is not your requested  server, then you can use following command

    " ssh-keygen -R IP_ADDRESS_OF_SERVER "

    This command will clear or delete the entry of public key for that particular IP present in known_hosts file and create new entry and old entries are stored in " known_hosts.old "

      Read More...

      Sunday, 28 April 2013

      Install Linux on External Hard Disk or Pen Drive

      Leave a Comment

       1. Why to install OS on external hard-disk or pen drive?

              The main reason is mobility. Carrying laptop every where is more difficult than carrying pen drive or External hard-disk. If you have any system available in your office or college, then you can simply do your work by booting through external hard-disk and after completing your work you can carry it to your home and restart the work by booting through external hard-disk.

      2. Requirement

      • External hard-disk with at least free space which fulfills the requirement of your OS.
      • Bootable CD/DVD or bootable pen drive.
      • Please check system hardware (which you want to access using OS installed on external hard-disk) whether it supports booting from USB or not. Many recent hardware support booting from external hard-disk or pen drive.

      3. How to install Linux on external hard-disk?

             First create one free partition which we can use for installing Linux as follow.
      1. Right click on My Computer in Windows OS then click on manage ->Storage ->Disk Management Then you will get screen as shown in image below.
             After this Right click on Disk 1 and click on Shrink Volume and follow the steps to create new disk drive.
      resize hard drive

             After creating free partition start installation as we do normal installation by restarting PC. You have to plug in external hard-disk or pen drive throughout  installation. Select installation type as "something else".


             First create boot sector with 500 MB which is require to store grub.

      Second create root drive with size you want to use for Linux.

      Third you must have to create swap partition which is used for storing swap files in hard disk which is faster than other drive.

      The main Part of your installation is selecting proper drive to install boot loader. You must select the drive partition which is used for the external hard disk. You can get list of drives by giving command " fdisk -l " in Linux or by going to computer management in Windows as shown earlier. In Linux for every new hard disk or pen drive it appends letter from a-z to sd*, sda is for first disk sdb is for second and so on. You can select proper drive as shown in following image.

      Now you can start installation by clicking install now.

      After completing installation restart your system go to boot menu
      Read More...

      Thursday, 25 April 2013

      Why Linux ?

      2 comments


      1. What is Linux.

            Linux is a open source operating system first release developed by Linus Torvalds in 5 Oct 1991. Linux kernel is developed in C language with GCC compiler. Linux is developed as open source Operating System (OS), so that any one can modify the kernel and get modified new OS as per the requirement. One most popular example is Android the widely used mobile OS which is developed by using Linux kernel. Almost all super computers run on Linux operating system due to its great reliability, security and open source features than Windows.

      2. Why Linux is not so popular

      • Linux is not user friendly as windows.
      • Installing and using different software in windows is much simpler and easier than Linux.

      3. Why to use Linux  

      • Virus won't affect.
      • Linux is available for free which make you free from using pirated copies of windows or purchasing its costly license copy.
      • It is open source that mean you can modify Linux kernel and develop your own OS.
      • Security of Linux is far stronger than windows which get affected by viruses and many other attacks.
      • Linux is very reliable OS which can run (continue) years without hanging. 

      4.Types of Linux operating System

      Widely we can categories Linux into three part
      • Red Hat Based (Red Hat, CentOS, Fedora etc.)
      • Debian Based (Ubuntu )
      • Slackware (SUSE) 

        4.1 Red Hat Based (CentOS, Fedora)

            This type  of OS is developed by rebuilding Red Hat Linux. This type of Linux uses RPM package manager. RPM refers to the .rpm package software used by Red Hat based OS. This are server end OS. This type of OS are very stable than other OS, but using this OS is difficult compared to other. Most famous OS in this type are CentOS, Fedora, Red Hat etc. Red Hat Enterprise linux is Commercial OS which is not free, but the redistribution of this OS such as CentOS, Fedora is freely available.

        4.2 Debian Based (Ubuntu ) 

           Debian is an association of people which makes open source OS. This type of OS are more user friendly than any other Linux OS, but using this type of OS at server end is not good. This OS contain many software packages around 29,000 present in official Debian distribution. Most famous OS in this type of distribution is Ubuntu.

        4.3 Slackware (SUSE)

          Slackware is earliest OS which modified Linux kernel so that Linux becomes more user friendly and stable. Most popular OS in this type is different SUSE distribution.

      5.  Which Linux Flavour to choose. 

            In my opinion one who is working in IT or CSE domain can use Red Hat based OS. In Red Hat based OS one can use CentOS since it is very stable and easy to use compared to other Red Hat based OS.
            General students can use Ubuntu or openSUSE which is very user friendly.

      Read More...