Thursday 31 October 2013

[Windows] Check and Fix file system errors of any memory card (flash memory devices)

On windows, we have a command called "chkdsk" (check disk) to verify the memory card's file system integrity and is used for checking file system errors and fix these errors if required.

This command is useful if the memory card is corrupted by some means and need to recover the data from the card without any data loss.

Step1) Insert the memory card (flash drive) which is corrupted or to check file system errors. After inserting the card, lets say the drive identified as E:/

Step2) Now, open command prompt and run chkdsk command
            chkdsk e: /f

Step3) You will see the info regd the file system used in the memory card and memory details. If the command identifies any file system errors then it fixes them.

The complete syntax for Check Disk is this:
 chkdsk [volume[[path]filename]]] [/F] [/V] [/R] [/X] [/I] [/C] [/L[:size]] 

Options:
-----------
Volume Sets the volume to work with.
filename FAT/FAT32 only: Specifies files to check for fragmentation.
/F Fixes errors on the disk.
/V On FAT/FAT32, this displays the full path and name of every file on the disk.
On NTFS, this displays cleanup messages, if any.
/R Locates bad sectors and recovers readable information (implies /F).
/L size NTFS only. Changes the log file size.
/X Forces the volume to dismount first if necessary (implies /F).
/I  NTFS only. Performs a minimum check of index entries.
/C NTFS only. Skips checking of cycles within the folder structure.

For more details please find useful linke here

On Linux platform, we have similar utility for checking and repairing file systems called "fsck". More details can be found here

Tuesday 29 October 2013

[C Programming] Implementation of Linked List in C

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

struct node {
  int data;
  struct node *next;
};

void insert_node(struct node **Head)
{
struct node *iterate;
int data;

printf("Enter node data:");
scanf("%d", &data);

if(*Head == NULL) {
*Head = (struct node*)malloc(sizeof(struct node*));
(*Head)->data = data;
(*Head)->next = NULL;
} else {
  iterate = *Head;
  while(iterate->next != NULL)
   iterate = iterate->next;
   iterate->next = (struct node*)malloc(sizeof(struct node*));
   iterate->next->data = data;
   iterate->next->next = NULL;
}
}

void show_linked_list(struct node *Head)
{
struct node *iterate = Head;

if(!iterate) {
      printf("Linked List is empty\n");
return;
}

printf("Linked List elements are\n");

while (iterate != NULL) {
     printf("%d\n", iterate->data);
 iterate = iterate->next;
}
}

void isLL_ContainLoop(struct node *Head)
{
struct node *start, *end = NULL;

start = Head;

do {
  if (start != NULL) {
  if(start->next)
 start = start->next->next;
    else
              start = start->next;
        }

        if (end == NULL)
           end = Head;
        else
           end = end->next;
}while(start != end && start!= NULL);

if (start == end && start != NULL)
  printf("+++Linked List has LOOP+++\n");
    else
  printf("+++Linked List has NO LOOP+++\n");
}

void cleanup(struct node **Head)
{
  struct node *iterate = *Head;
  while(*Head)
  {
iterate = (*Head);
*Head = (*Head)->next;
iterate->next = NULL;
free(iterate);
}
}

struct node* search_node(struct node *Head, int data)
{
  while (Head) {
  if (Head->data == data)
   return Head;
  Head = Head->next;
  }
  return NULL;
}


void delete_node(struct node **Head)
{
  struct node *del_node = NULL;
  struct node *iterate = *Head;
  int data, find;
 
  if (*Head == NULL)
  printf("Linked List is empty\n");

  show_linked_list(*Head);
  printf("Select data to delete from linked list\n");
scanf("%d", &data);

del_node = search_node(*Head, data);
if (del_node) {
  printf("Data is present\n");

    if (del_node == *Head) {
        *Head = (*Head)->next;
        iterate->next = NULL;
        free(iterate);
    } else {
  while (iterate->next != del_node)
    iterate = iterate->next;
           iterate->next = iterate->next->next;
           del_node->next = NULL;
           free(del_node);
              }

} else {
  printf("Data is not present\n");
}
}

void main()
{
struct node *Head = NULL;
int choice, data;

while(1) {
printf("****Menu*****\n");
printf("select 1: Insert new node\n");
printf("select 2: show linked list elements\n");
printf("select 3: is Linked list contain loop\n");
printf("select 4: Delete node\n");
printf("select 5: Search node\n");
printf("select 6: Exit\n");
printf("Enter your input 1-6 ?\n");
scanf("%d", &choice);

switch(choice){
case 1: insert_node(&Head); break;
case 2: show_linked_list(Head); break;
case 3: isLL_ContainLoop(Head); break;
case 4: delete_node(&Head); break;
case 5: printf("Enter Data to search in Linked List\n");
scanf("%d", &data);
if (search_node(Head, data)) printf("Data is present\n");
   else printf("Data is not present\n");
    break;
case 6:
        default: cleanup(&Head); exit(1);
}
printf("=========================\n");
    }
}

Output:
-----------
****Menu*****
select 1: Insert new node
select 2: show linked list elements
select 3: is Linked list contain loop
select 4: Delete node
select 5: Search node
select 6: Exit
Enter your input 1-6 ?
1
Enter node data:11
=========================
****Menu*****
select 1: Insert new node
select 2: show linked list elements
select 3: is Linked list contain loop
select 4: Delete node
select 5: Search node
select 6: Exit
Enter your input 1-6 ?
1
Enter node data:22
=========================
****Menu*****
select 1: Insert new node
select 2: show linked list elements
select 3: is Linked list contain loop
select 4: Delete node
select 5: Search node
select 6: Exit
Enter your input 1-6 ?
2
Linked List elements are
11
22
=========================
****Menu*****
select 1: Insert new node
select 2: show linked list elements
select 3: is Linked list contain loop
select 4: Delete node
select 5: Search node
select 6: Exit
Enter your input 1-6 ?
3
+++Linked List has NO LOOP+++
=========================
****Menu*****
select 1: Insert new node
select 2: show linked list elements
select 3: is Linked list contain loop
select 4: Delete node
select 5: Search node
select 6: Exit
Enter your input 1-6 ?
5
Enter Data to search in Linked List
22
Data is present
=========================
****Menu*****
select 1: Insert new node
select 2: show linked list elements
select 3: is Linked list contain loop
select 4: Delete node
select 5: Search node
select 6: Exit
Enter your input 1-6 ?
4
Linked List elements are
11
22
Select data to delete from linked list
11
Data is present
=========================
****Menu*****
select 1: Insert new node
select 2: show linked list elements
select 3: is Linked list contain loop
select 4: Delete node
select 5: Search node
select 6: Exit
Enter your input 1-6 ?
2
Linked List elements are
22
=========================
****Menu*****
select 1: Insert new node
select 2: show linked list elements
select 3: is Linked list contain loop
select 4: Delete node
select 5: Search node
select 6: Exit
Enter your input 1-6 ?
6

Monday 28 October 2013

[C Programming] Find roots of any quadratic equation

#include<stdio.h>
#include<math.h>

void main()
{
  int coefficient_a, coefficient_b, coefficient_c;
  int delta;
  float root1, root2;
  float temp;
 
  printf("Enter values for coefficients a, b and c\n");
  scanf("%d%d%d", &coefficient_a, &coefficient_b, &coefficient_c);
 
  printf("Entered expression is\n");
  printf("%dx^2 + %dx + %d\n", coefficient_a, coefficient_b, coefficient_c);
 
  if (!coefficient_a) {
  printf("Entered equation is not a quadratic equation, since coefficient_a is ZERO\n");
  return;
     }

  delta = (coefficient_b * coefficient_b) - (4 * coefficient_a * coefficient_c);
 
  if (delta > 0){
  /* Roots are Real numbers */
  printf("Roots are Real numbers\n");
  root1 = (-coefficient_b + sqrt(delta)) / (2 * coefficient_a);
  root2 = (-coefficient_b - sqrt(delta)) / (2 * coefficient_a);
 
  printf(" Roots are %f and %f\n", root1, root2);
  }
  else {
 /* Roots are imaginary numbers
  * roots = (-b +- i sqrt(4*a*c-b*b)) / (2*a)
  * temp = -b/2*a;
  * root1 = temp + i sqrt(4*a*c-b*b)/(2*a);
  * root2 = temp - i sqrt(4*a*c-b*b)/(2*a);
  */
 printf("Roots are imaginary numbers\n");
 temp = -coefficient_b / (2 * coefficient_a);
 root1 = sqrt(-delta) / (2 * coefficient_a);
   root2 = -sqrt(-delta) / (2 * coefficient_a);
   printf(" Roots are %f + i(%f) and %f + i(%f)\n", temp, root1, temp, root2);
  }
}

Output1:
---------
Enter values for coefficients a, b and c
1
5
6
Entered expression is
1x^2 + 5x + 6
Roots are Real numbers
 Roots are -2.000000 and -3.000000


Output2:
-----------
Enter values for coefficients a, b and c
1
2
8
Entered expression is
1x^2 + 2x + 8
Roots are imaginary numbers
 Roots are -1.000000 + i(2.645751) and -1.000000 + i(-2.645751)

[C Programming] Find Maximum and Minimum number in array of numbers

#include<stdio.h>
#define ARRAY_SIZE 100 /* Define Your ARRAY Size */

int find_max(int input[], int size)
{
  int max, index;
 
  max = input[0];
 
  for (index = 1; index < size; index++)
  {
if (max < input[index])
  max = input[index];
    }
    return max;
}

int find_min(int input[], int size)
{
  int min, index;
 
  min = input[0];
 
  for (index = 1; index < size; index++)
  {
if (min > input[index])
  min = input[index];
    }
    return min;
}

void main()
{
  /* We can dynamically allocate memory for an array using malloc() based on array_size requested from end user*/
  int set_of_numbers[ARRAY_SIZE];
  int size, index;
  int maximum, minimum;
 
  printf("Please enter number list size\n");
  scanf("%d", &size);
 
  if (size <= 0) {
  printf("Please enter valid size\n");
  return;
     }

  printf("Enter numbers\n");
  for (index = 0; index < size; index++)
  scanf("%d", &set_of_numbers[index]);

printf("List of numbers entered by user\n");
  for (index = 0; index < size; index++)
  printf("%d\n", set_of_numbers[index]);
 
  maximum = find_max(set_of_numbers, size);
  minimum = find_min(set_of_numbers, size);
 
  printf("Maximum number: %d\n", maximum);
  printf("Minimum number: %d\n", minimum);
}

Output:
-----------
Please enter number list size
5
Enter numbers
12
34
2
7
8
List of numbers entered by user
12
34
2
7
8
Maximum number: 34
Minimum number: 2

[Kernel Programming #7] ktime_get() and do_gettimeofday() APIs use

We have some APIs to measure time taken for a function or a piece of code in the driver.

1. do_gettimeofday()
2. ktime_get()

These APIs are used to measure the time (absolute timestamp) in the kernel.
do_gettimeofday() gives microsecond precision.
ktime_get() return ktime_t object, which has nano second precision.

ktime_get:

===========
Here is abstract code to show how ktime_get() API will be used in our driver to measure time taken for a function.

The prototype for ktime_get is:

 #include <linux/ktime.h>
 ktime_t ktime_get(void);

Sample-code:
--------------
ktime_t start, end;
s64 actual_time;

start = ktime_get();

function();
/* or piece of code */
....
....

end = ktime_get();

actual_time = ktime_to_ns(ktime_sub(end, start));

printk(KERN_INFO, "Time taken for function() execution: %lld\n",
(long long)actual_time);

/* Use below code for millisec precision */
actual_time = ktime_to_ms(ktime_sub(end, start));

printk(KERN_INFO, "Time taken for function() execution: %u\n",
(unsigned int)actual_time);


do_gettimeofday():

==================
Here is abstract code to show how do_gettimeofday API will be used in our driver to measure time taken for a function.

The prototype for do_gettimeofday is:

 #include <linux/time.h>
 void do_gettimeofday(struct timeval *tv);

When this function called, it fills the timestamp data in struct timeval.

Using struct timeval members, we can extract seconds and microseconds info.

Sample code:
-------------
do_gettimeofday(&tstart);

/* Function or code to measure time bound */

do_gettimeofday(&tend);

printk("time taken: %ld millisec\n",
1000 * (tend.tv_sec - tstart.tv_sec) +
(tend.tv_usec - tstart.tv_usec) / 1000);

Sunday 27 October 2013

SQL Injection Attack Presentation

Ubuntu Basic Commands

There are few simple commands in Ubuntu operating system those we should know before using any Ubuntu machine. These commands would be very helpful and are easy for Ubuntu machine maintenance.

Man Pages

Linux OS provides a command named "man" for reading manual pages in the system. These manual pages contains description of general commands, system calls functions, library functions, file formats conventions etc.
These pages provides insight information of above mentioned categories.

man <command_name>

Example:
If something (like printf() function in C language) is not clear, what it do, what is the use and what is the syntax of this function etc information can be found in printf man pages. Below command should be used for this purpose

man printf

Similary, if we are not clear about any command, what it is, its use, where to use etc info is available in the manual pages
Try: man sudo

Once the manual page is opened in the terminal, use letter "q" to exit from the manual page.
-------------------------------------------------------------------------------------

"Sudo" Importance

In order to do administrative tasks like install, remove or upgrade applications/software in the Ubuntu machine, the logged user should have administrator privileges.
For this purpose, Ubuntu environment provides a special command called "sudo" (Super Used DO), which will allows us to install/remove/upgrade and system maintenance.
In Ubuntu there is no way to log in as Admin user (log in as ROOT) to do above tasks. So, Ubuntu added this command specifically to support above tasks.

Installing any application/software
Use: sudo apt-get install <package_name>

Un-Installing any application/software
Use: sudo apt-get remove <package_name>

Upgrade system software/applications
Use: sudo apt-get upgrade

sudo command will run the commands in administrator mode.

In ubuntu, all the application software are available in repositories unlike windows machine where we need to carry the software in external storage.

So, when we use command "apt-get", it will search required software/s (<package_name>) in the repositories, get that software program and will install/upgrade it without user intervention. It will automatically install software for us.
Note: Our Ubuntu machine should have Internet connection to use this facility from Ubuntu.
-----------------------------------------------------------------------------------------

Tasksel:

Tasksel (Task select) is also a special command in Ubuntu environment to install set of packages in one go.
For example, if we want to install FTP server or printer server or DNS server, they require so many dependency packages to install in order one by one to work.
Instead of installing them manually one by one, Ubuntu environment provides scripts for us to do above tasks using tasksel command. These scripts will have all information about the software and installs all required packages.
So, we don't need to worry about the dependency packages need to install before installing desired program.

Use: sudo tasksel
Result: It will promt a window, where we can select the software need to install from pre-avialble software lists (ex: DNS server, FTP server, Email sever etc). Select the required options and click OK. Done. 

-----------------------------------------------------------------------------------------

Control the service:
We can restart/start/stop any service using below command

Use:

sudo /etc/init.d/<service_name> start
sudo /etc/init.d/<service_name> stop
sudo /etc/init.d/<service_name> restart
-----------------------------------------------------------------------------------------

TOP command

The command "top" is very much similar to task manager in windows system.
Using top command, we will see the data like CPU utilization and memory utilization per process and in addition processes info that are running etc.

Use: sudo top
Task Manager in the UNIX world.
We see process ids (PID), CPU utilization and memory utilization info.

Abort any process using command "kill"
Use: 
kill -9 <process_id>
or
pkill -9 <process_name>
---------------------------------------------------------------------------------------

Navigation:

Navigation between the directories are simple in linux environment using command "cd" (Change Directory)

Use:
cd <directory_name>
   -->means that change the current working directory to <directory_name>

cd /<directory_name>
  --> means that change the directory to <directory_name> under ROOT (/) directory.

Under ROOT, we do find the directories named "home", "etc" and others.
So, if we need to navigate to any directories under ROOT (/) then use slash (/) before that directory name
i.e.  cd /home

Saturday 26 October 2013

Blog Tips

Add any gadgets like Recent Post, Popular Posts and labels etc. in just 3 steps.

  1. Go to Layout section in your blog
  2. Select Add a Gadget option
  3. Choose gadgets from the pop-up list and SAVE it.

Add  PowerPoint Presentation (ppts) in your blog post

I added the same using slideshare.net option.
Here are the simple steps to add a ppt (which is available in our PC) in blog post without any coding.
  1. Create an account in slideshare.net
  2. Upload your ppt in slideshare with your account
  3. Open your ppt in slideshare after uploading it
  4. You will see an option Embed. Select it. Then copy and paste the URL code into your blog.
  5. Select HTML option in the blog post and paste above URL just before closing </div>
  6. Set Title to your post and SAVE it.
You can see your ppt in your blog post. My ppt can be found at Compilation Process in C

I followed below instructions to do the same.
Add PPT to your blogger using slideshare

Add Table in your blog post

We can add a table structure in the blog post using below simple steps
  1. Prepare table data in excel sheet (or Microsoft word document) and select the table and copy it.
  2. Go to tableizer, used this site to convert our table form data into HTML form data. Paste copied table data in the text-box of Tableizer page.
  3. Now, select "Tableize It" button. We will get HTML ouput for our table data.
  4. Copy this HTML data and paste in our blog's HTML post. Set title to the post and SAVE it. 
Now, table format data will be appeared in our blog post.
I followed above steps to add table in my blog post titled Differences between 1G, 2G, 3G and 4G Technologies

Compilation Process in C



Compiling a C Program:

gcc <options> program_name.c

Options:
-----------
-Wall: Shows all warnings
-o output_file_name: By default a.out executable file is created when we compile our program with gcc. Instead, we can specify the output file name using "-o" option.
-g: Include debugging information in the binary.


Linking Multiple files to make executable file:

If we have two programs say prog1.c and prog2.c for one single task then we can make single executable file using following instructions

First, compile these two files with option "-c"
gcc -c prog1.c
gcc -c prog2.c

-c: Tells gcc to compile and assemble the code, but not link.

We get two files as output, prog1.o and prog2.o
Now, we can link these object files into single executable file using below instruction.

gcc -o prog prog1.o prog2.o

Now, the output is prog executable file.
We can run our program using
./prog


Linking with other libraries:

Normally, compiler will read/link libraries from /usr/lib directory to our program during compilation process.
But, there are some case where we need to link our programs with libraries like pthreads and realtime libraries (rt library).
Use below instruction for this purpose

gcc <options> program_name.c -lpthread -lrt

-lpthread: Link with pthread library
-lrt: Link with rt library
Option here is "-l<library>"

Another option "-L <dir>" used to tell gcc compiler search for libraries in given <dir> directory.

Friday 25 October 2013

Differences between 1G, 2G, 3G and 4G Technologies


1G2G3G4G
VoiceVoice + DataVoice + Data + Video (Broadband). Video conference.Long Term Evaluation (LTE) (Ultra-Broadband). Online Multi-media newspaper and TV prog.
Narrow band analog wireless NetworkNarrow band wireless Digital networkWide band wireless networkWide band wireless network
Service is provided using Circuit SwitchingUsing Circuit SwitchingData service uses Packet Switching. Voice calls uses Circuit Switching.Same as 3G service with faster service rate
Internet connectivity: NoneYesYes. Faster compare to 2GYes. Faster compare to 3G
Uses following standards: AMPS NMT TACSUses following standards: GSM CDMA TDMAUses following standards: UMTS CDMA2000Uses following standards: WIMAX
Data Rate: 14.4KbpsData Rate: 144KbpsData Rate: 2Mbps Download speed: Up to 42MbpsData Rate: 2Mbps to 156 Mbps or higher. Download speed: up to 100Mbps

More the G number is bigger faster we get in internet/data services and online multi-media programs with less latency possible.


Please refer below links for more details on the telephone technology

Tuesday 22 October 2013

Using Spreadsheet (excel sheet)

Here are the few useful websites info on using spreadsheets.

Extract a Substring Using the MID Function in Excel
Please go through below page for more details.
http://spreadsheets.about.com/od/Text-Functions/ss/2011-01-31-excel-2010-truncate-text-strings-mid-function.htm

http://spreadsheets.about.com/od/excel2010functions/ss/2011-01-30-excel-2010-truncate-text-strings-right-function.htm

Subtraction of two numbers:
column1 column2    output_column
  12          14           =column1-column2

Enter the computational string "=column1-column2" in the column where you need the result of subtraction of two numbers. Since, we don;t have any function in function list like SUM and AVERAGE etc.

If I find anything new about using spread sheets then will add it here.




Sunday 20 October 2013

Strings concepts in C

We can store a string ("sachin", "ram", etc.) using a character array and using a character pointer in C.

Using character array:

A character array is declared as below
char var[] = "sachin";
char var[7] = {'s', 'a', 'c', 'h', 'i', 'n', '\0'}; /* '\0' is string terminator */
/*One extra for string terminator*/
char var[7] = "sachin";

If this string variable is declared in a function then the variable data is stored in stack segment. So, it is possible to modify the content of the string.
var[1] = 'A';

If the string is a global or static variable then it is stored in data segment.
So, the content of the variable can also be modified like,

var[2] = 'C';
var[3] = 'H';

Using character pointer:

A character pointer is declared in two ways.

case-1:

char *var = "sachin";

Here, the string "sachin" is directly assigned to character pointer and it is stored in Read-only memory of of data segment.This string can be shared among functions unlike character arrays. Since this memory is read-only memory, it is not possible to modify the content of the string.

case-2:

char *var = (char *)malloc(sizeof(char) * 7);
var = "sachin";

Here, the string "sachin" is assigned to character pointer which memory is dynamically allocated using malloc(). So, the string memory is allocated in Heap segment.

This string can be shared among functions unlike character arrays. It is stored in Read-write memory (Heap segment), so it is possible to modify the content of the string.

  *(var+0) = 'S';
  *(var+1) = 'a;
  *(var+2) = 'c';
  *(var+3) = 'h';
  *(var+4) = 'i;
  *(var+5) = 'n';  
  *(var+6) = '\0';
  *(var+1) = 'A';  /* No problem: String is now SAchin */

But, if you assign string "sachin" directly to var character pointer and if we want to edit the string then it is not possible. We will see error.

Example:
char *var = (char *)malloc(sizeof(char) * 7);
var = "Sachin";
 *(var+1) = 'A';  /* problem seen */

Using malloc(), a memory of 7 Bytes is allocated in Heap segment and that address is passed to var.

Now, if we assign any string (of size less than or equal to 7) to this var variable then var points to the address of this string which is allocated in Read-Only memory. Because, compiler allocates memory for string "Sachin" in Read-only memory and this address is copied into var character pointer.
So, it is not possible to modify the string of this memory. It falls under case-1 scenario.

Note-1: Benefit from character pointer is that we can share the address of the string among functions.

Sample code for Note-1:
------------------------------

#include<stdio.h>

char* character_pointer_fun()
{
  char *str = "Using character pointer";
 
  return str;
}

char* character_array_fun()
{
  char str[] = "Using character array";
 
  str[1] = 'S';

  return str;
}

int local_var()
{
  int a =111;
  return a;
}

void main()
{
  char *char_ptr_str;
  char *char_array_str;
  int a;
 
  char_ptr_str = character_pointer_fun();
  printf("In main: %s\n", char_ptr_str);
 
  char_array_str = character_array_fun();
  printf("In main: %s\n", char_array_str);
 
  a = local_var();
  printf("In main: local var: %d\n", a);
}

Output:
----------
In main: Using character pointer
In main: USing character array /* Not expected output */
In main: local var: 111 /* Not expected output */

The last two lines output are not expected. Since, after function is returned the stack memory will be cleared for that function.
So, we may or may not see the correct value for local variable and a string which is defined as character array.

How to check if a given number is Fibonacci number?

Fibanacci numbers have one interesting property:
A number 'n' is a Fibanacci number if and only if (5*n*n + 4) or (5*n*n - 4) or both are perfect squares.

The below program will find whether input number is fibanacci number or not.

We have an alternate method also to find a number is fibanacci or not by generating fibanacci numbers until the value is equal to or greater than input number. But, this method is time consuming one. So, we are using fibanacci numbers property.

Code:

#include<stdio.h>
#include<math.h>

int isPerfectsquare(int input)
{
int result;

  result = sqrt(input);
if (result * result == input)
  return 1;
  else
     return 0;  
}

int isFibanacci(int input)
{
  int result;
 
 /* If return value of 
  sqrt(5*input*input + 4) or 
  sqrt(5*input*input - 4) is perfect sqaure then
  input number is fibanacci
  */

result = isPerfectsquare(5 * input * input + 4) || isPerfectsquare(5 * input * input - 4);
if (result)
   return 1;
  else
  return 0;
}

main()
{
   int input, result;

   printf("Enter a number to verify whether it belongs to fibanacci number set\n");
   scanf("%d", &input);
   
   result = isFibanacci(input);
   
   if (result)
      printf("Given number %d is fibanacci number\n", input);
  else
     printf("Given number %d is not fibanacci number\n", input);
}

Output:
Enter a number to verify whether it belongs to fibanacci number set
13
Given number 13 is fibanacci number

What is a fibanacci number ?
http://en.wikipedia.org/wiki/Fibonacci_number

How to recognize a fibanacci number
http://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers


Saturday 19 October 2013

How to remove specific website history in Chrome

The following options will be found in history page of chrome.

  1. Clear history for specific day
  2. Clear history for a longer period of time

But, we don't find any option to remove specific website history from history list.

Google Chrome Extension eHistory will add this option also
https://chrome.google.com/webstore/detail/ehistory/hiiknjobjfknoghbeelhfilaaikffopb
Add eHistory extension to your chrome.
Now, we find a search box in history page. Search specific websites and remove.

Simple..!!!

New incognito window (CTRL+SHIFT+N) option will not save any browsing history. But, eHistory extension adds additional feature like removing specific websites from history page.

Friday 18 October 2013

Where does Chrome store it's bookmarks?

You can export your bookmarks from Google chrome in this way: 

  1. Click the wrench icon on the browser toolbar. 
  2. Select Bookmark manager. 
  3. Click the Organize menu in the manager. 
  4. Select Export bookmarks. 
  5. Choose a location where you want your exported file to be saved, then click Save. 
  6. Google Chrome will export your bookmarks as a HTML file. 


Really helpful info.

Install Adobe Acrobat Reader in Ubuntu

Install Adobe Acrobat Reader in Ubuntu pc
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Approach-1: Didn't work for me
----------------------------------
Step1) sudo add-apt-repository "deb http://archive.canonical.com/ precise partner"
Step2) sudo apt-get update
Step3) sudo apt-get install acroread
=============================
Result:
--------
Reading package lists... Done
Building dependency tree    
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
  acroread: Depends: acroread-bin but it is not installable
E: Broken packages


Approach-2: Didn't work for me
-------------------------------
Download Adobe*.deb (i386 version .deb file) from ftp://ftp.adobe.com/pub/adobe/reader/unix/9.x/


sudo linux32 dpkg -i AdbeRdr9.5.4-1_i386linux_enu.deb
=======================================================
dpkg: error processing AdbeRdr9.5.4-1_i386linux_enu.deb (--install):
 package architecture (i386) does not match system (amd64)
Errors were encountered while processing:
 AdbeRdr9.5.4-1_i386linux_enu.deb

Approach3: Worked for me..hurray...
----------------------------------------
sudo dpkg -i --force-architecture AdbeRdr9.5.4-1_i386linux_enu.deb
=====================================================
dpkg: warning: overriding problem because --force enabled:
 package architecture (i386) does not match system (amd64)
Selecting previously deselected package adobereader-enu.
(Reading database ... 147879 files and directories currently installed.)
Unpacking adobereader-enu (from AdbeRdr9.5.4-1_i386linux_enu.deb) ...
Setting up adobereader-enu (9.5.4) ...

Processing triggers for man-db ...

Reference for Approach-3: http://notepad2.blogspot.in/2011/04/install-adobe-reader-on-64-bit-ubuntu.html


Wednesday 16 October 2013

Linux Kernel Version Numbering Methodology

Linux Kernel Version numbering Mechanism:

We can differentiate linux kernel using its version and these versions are mainly two types.

  1. Stable version
  2. Development version

At any point of time, we have many stable linux versions but only one development version.

Linux kernel version numbering system follows a 4 number system
X.Y.Z.W

X --> Kernel Version.
It is incremented when
a really significant changes happen in Kernel
major changes in the concepts and the code of the kernel.

Y --> Major revision of the kernel.
If this number is an even number then it is a stable kernel (Production use)
If it is odd then it is a development kernel
Developers actively work on Development kernel only.
Example: Current stable version is 2.4.x, and development version is 2.5.x
Once the development in 2.5.x is done, eventually it will become 2.6.0 kernel and new stable kernel is then established.
So, 2.7.x series will begun for development.
If only major changes happen, 2,5,x become 3.0.0 and 3.1.x is open for developers.

Z --> Minor revision of the kernel
It will be changes when a new feature or driver is added.

W --> Represents corrections such as security patches and bug fixes.

We can use "uname" command with option "r" to see which release of the kernel is being used in our linux system.
uname -r
Result in my pc: 2.6.32-28-generic

Reference:
http://www.tldp.org/FAQ/Linux-FAQ/kernel.html#linux-versioning
http://www.linfo.org/kernel_version_numbering.html


Sunday 6 October 2013

[Operating Systems #3] Sigaction API C code examples

Please refer previous posts for understanding the concepts related to asynchronous signals and useful APIs (including signal API and sigaction API)

Example-1
=========
/*
 *  Child process auto clean-up using sigaction API.
 * If child process is done with its task, then it will be pushed to defunc state.
 * Parent process has to instruct the Kernel Process Manager to destroy the child process using wait function. Instead of blocking parent process until child process termination, we use sigaction API.
 * Using sigaction(), we register a function call back sighandle(), this function will be called when child process has done with its task. In the mean time, parent process can do its own task without dependent on child process.
*/

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

void sighandler (int signum)
{
printf("Sighandler: I am in sighandler\n");
}

void main()
{
struct sigaction act;
pid_t cpid;

memset(&act, 0, sizeof(act));

act.sa_handler = sighandler;
act.sa_flags = SA_NOCLDWAIT; /* Setting up auto clean-up */

if (sigaction(SIGCHLD, &act, NULL) < 0)
printf("Sigaction reg is failed\n");

cpid = fork();

if (cpid == 0) {
printf("Child: I am in child process\n");
sleep(8);
printf("Child: Done with its task\n");
}
else {
printf("Parent: I am in parent process\n");
while (1) {
printf("main: in loop\n");
sleep(2);
}
}
}

Output:
========
Parent: I am in parent process
main: in loop
Child: I am in child process
main: in loop
main: in loop
main: in loop
Child: Done with its task
Sighandler: I am in sighandler
main: in loop
main: in loop
main: in loop
main: in loop
main: in loop
^C

Observation:
==============
When child and parent process are executing.
rrajk      3044  2067  0 08:56 pts/0    00:00:00 ./sigaction_child
rrajk      3045  3044  0 08:56 pts/0    00:00:00 ./sigaction_child

Once child terminated, sighandler will be called.
rrajk      3044  2067  0 08:56 pts/0    00:00:00 ./sigaction_child

Since we set flag SA_NOCLDWAIT, the child process is destroyed once its done its task.
Otherwise it would be pushed to defunc state.




Example-2
=========
/*
 * Blocking a signal of type 'Y' if another signal of type 'X' is in its handler.
 * Once signal X is completed its task, signal Y's handler is invoked.
 * Use sigaddset() with sigaction() API
*/

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

void sighandler (int signum)
{
printf("Sighandler: I am in sighandler before sleep\n");
sleep(3);
printf("Sighandler: I am in sighandler after sleep\n");
}

void main()
{
struct sigaction act;
sigset_t sigmask;
int rc;

memset(&act, 0, sizeof(act));
rc = sigemptyset(&sigmask);
printf("sigemptyset return value: %d\n", rc);

rc = sigaddset(&sigmask, SIGQUIT); /* Block this signal if the process is in its handler */
rc = sigaddset(&sigmask, SIGTERM); /* same above */
printf("sigaddset return value: %d\n", rc);

act.sa_handler = sighandler;
act.sa_mask = sigmask;

if (sigaction(SIGINT, &act, NULL) < 0)
printf("Sigaction reg is failed\n");

while (1) {
printf("main: in loop\n");
sleep(2);
}
}

Output:
========
sigemptyset return value: 0
sigaddset return value: 0
main: in loop
main: in loop
main: in loop
^CSighandler: I am in sighandler before sleep
^\Sighandler: I am in sighandler after sleep
Quit (core dumped)

Observation:
==============
If CTRL+C is generated and this signal is in its handler. Now, CTRL+\ (SIGQUIT) is gernerated then it will be blocked until
CTRL+C handler completes its execution.
Once CTRL+C handler done with its task then CTRL+\ handler will be executed.


Example-3
=========
/*
 * sa_flags member in sigaction structure usage.
*/

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

void sighandler (int signum)
{
printf("Sighandler: I am in sighandler\n");
sleep(3);
}

void main()
{
struct sigaction act;

memset(&act, 0, sizeof(act));

act.sa_handler = sighandler;
act.sa_flags = SA_NODEFER; /* Do not prevent the signal from being received from within its own sighandler */

if (sigaction(SIGINT, &act, NULL) < 0)
printf("Sigaction reg is failed\n");

while (1) {
printf("main: in loop\n");
sleep(2);
}
}

/*Output:
========
main: in loop
main: in loop
^CSighandler: I am in sighandler
^CSighandler: I am in sighandler
^CSighandler: I am in sighandler
^CSighandler: I am in sighandler
main: in loop
main: in loop
main: in loop
main: in loop
main: in loop
main: in loop
^CSighandler: I am in sighandler
^CSighandler: I am in sighandler
main: in loop
User defined signal 1

Observation:
==============
SA_NODEFER flag usage. Since we set the flag NODEFER, the signals are delivered to registered process without any delay once they are generated. So, we saw "I am in sighandler" for 4 times (I pressed CTRL+C 4 times).
If we remove this flag then the behavior is different. Please refer post #2 sigaction section.
Try at your end by commenting SA_NODEFER line and observe the output.



Wednesday 2 October 2013

[Operating Systems #2] ASynchronous Signals handling using signal and sigaction APIs

Please refer previous post #1: Handling child process. Since, current post is continuation of the post #1.

We already see the use of wait() function. This function call blocks the parent process, reads the exit value of child process and instructs the kernel's process manager to destroy the child process.

Wait() function is synchronous call, it will suspend/block the execution of parent process i.e. parent can't continue its operation/execution until child terminates.

Now, we will see another API "Signals" which uses Asynchronous method.
This method allows the parent process to register a function call back. This function will be executed when the child process terminates. So, the child and parent process can be executed simultaneously without any parent blocking.

Here, we have two different APIs to do this job.

  1. Signal API
  2. Sigaction API

Signal API :
=========

Signals are asynchronous calls, means these will block current execution of process and requires immediate response (registered function call be will be called automatically when the signal interrupt is received).

Once the signal is received, the process can able to perform three different tasks
  1.  Calls default signal handler
  2.  Calls its own defined signal handler
  3.  Ignores the signal
The below Sample code will describe the use of 2nd case (process calls its own defined signal handler).

For 1st case, pass second argument as SIG_DFL in signal() function call. Kernel process manager will call the default function for the signal generated.

For 3rd case (Ignore the signal), use 2nd argument as SIG_IGN in signal() function.

-------------------------------------------------------------------------------------------
Sample code:
----------------

  1. #include<unistd.h>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<signal.h>

  5. #define CHILD 0

  6. void sighand(int signum)
  7. {
  8. printf("I am in signal handler: %d\n", signum);
  9. }
  10. int main()
  11. {
  12. pid_t child_pid;

  13. child_pid = fork();
  14. if (child_pid == CHILD) {
  15. /* child process */
  16. printf("child: %d, parent: %d\n", getpid(), getppid());
  17. sleep(10);
  18. exit(100);
  19. } else {
  20. /* parent process */
  21. signal(SIGCHLD, sighand);
  22. printf("Successfully registered sighand for SIGCHLD: %d\n", SIGCHLD);
  23. printf("parent: %d\n", getpid());
  24. while(1) {
  25. printf("in parent\n");
  26. sleep(2);
  27. }
  28. }
  29. return 0;
  30. }

output:
=======
Successfully registered sighand for SIGCHLD: 17
parent: 2274
in parent
child: 2275, parent: 2274
in parent
in parent
in parent
in parent
in parent
I am in signal handler: 17
in parent
in parent
in parent
.
.

observation:
=========
signal is not a blocking call like wait().
Since in wait() case, parent process is blocked until child terminated.
But here in signal() case, parent process is executing continuously and received asynchronous interrupt (SIGCHLD) when child terminates. sighand() is called in response to this interrupt.
ps -Af (Before SIGCHLD interrupt received)
-----------------
rrajk      2285  2039  0 10:59 pts/0    00:00:00 ./fork4_signal
rrajk      2286  2285  0 10:59 pts/0    00:00:00 ./fork4_signal

ps -Af (After SIGCHLD received:)
----------------
rrajk      2285  2039  0 10:59 pts/0    00:00:00 ./fork4_signal
rrajk      2286  2285  0 10:59 pts/0    00:00:00 [fork4_signal] <defunct>

Since child process terminated, but parent process is still executing then child process put into defunc state.
------------------------------------------------------------------------------------------

Sigaction API:
============

Signal API is an ANSI C Standard API.
Sigaction API is a POSIX standard API.

We use sigaction APIs for changing the signal disposition in better way compared to signal.
Using sigaction, we can block/unblock required set of signals with ease of operations.

Sigaction() prototype declaration
--------------------------------------
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);

struct sigaction {
  void (*sa_handler)(int);
  void (*sa_sigaction)(int, siginfo_t *, void *);
  sigset_t sa_mask;
  int sa_flags;
  void (*sa_restorer)(void);
};

sigaction is alternative signal API for changing signal disposition.
Sample code:
            struct sigaction sa;
            memset(&sa, 0, sizeof(sa));
  
          /* Install signal Handler */
            sa.sa_handler = handler;
            if (sigaction(SIGALRM, &sa, NULL) < 0)
                        printf(“Sigaction failed\n”);

When a signal is generated and it is being currently handled, another occurrence of the same signal shall be queued (queue size = 1) until handler returns. If more than 1 signal is generated in this case, they will be lost.

But, occurrence of Real Time signals are never lost, they will be queued.

sa.sa_flags:
==========
           sa.sa_flags = SA_NODEFER;
           Signals are not queued, they directly send to the registered process. No delay in delivery. No queue also.

sa.sa_mask:
==========
If one signal is in its handler, and if another signal is generated then 1st signal is terminated immediately and 2nd signal handler will start its execution.
Ex: CTRL+C SIGTERM and CTRL+\ SIGQUIT

Sigaction provide a mechanism to block this 2nd signal until 1st signal completed its handler function.
Sample code:
            sigset_t sigmask;
            sigemptyset(&sigmask);

            sigaddset(&sigmask, SIGQUIT); /* block SIGQUIT if a signal is already in its handler */
            sigaddset(&sigmask, SIGTERM);

            sa.sa_handler = handler;
            sa.sa_mask = sigmask;

            if (sigaction(SIGINT, &sa, NULL) < 0)
                        printf(“sigaction is failed\n”);

Sigprocmask:
=============
Applications can also block/unblock signal delivery while executing the primary functionality in the main thread.
            Int sigprocmask(int how, const sigset_t *set, sigset_t *old_set);

how: SIG_BLOCK or SIG_UNBLOCK

Sample code:
            struct sigaction sa;
            sigset_t set;

            memset(&sa, 0, sizeof(sa));
            sigemptyset(&set);

            sigaddset(&set, SIGQUIT);
            sigaddset(&set, SIGTERM);

            /* ovrride signal mask set */
            sigprocmask(SIG_BLOCK | SIG_SETMASK, &set, NULL);

           /* Append to signal mask list */

            sigprocmask(SIG_BLOCK, &set, NULL); 

Examples will be posted in next post [Operating Systems #3].

You might also like

Related Posts Plugin for WordPress, Blogger...