Monday 16 December 2013

[C Programming] Function Pointers basics in C

Function Pointers

Definition

Function pointers are pointers, which points to the address of a function. Function pointers are variables only, so it will be declared and defined like other variable.

Syntax

<data_type> (*function_pointer_name) (variable data_type list) = NULL; /* defining function pointer and initializes to NULL */

The signature of this function pointer should match with the signature of function which address is stored in this pointer.

Sample code

float doMath (float a, float b) {
 /*
    desired code
 */
return result;
}

int main() {
float (*math_pointer) (float, float) = NULL;

math_pointer = &doMath; /* pointer to function doMath() */

output = math_pointer (10.5, 11.1);
/*
   desired code
*/
return 0;
}


Usage

  1. To replace switch/if conditional statements
  2. To implement late-binding (runtime binding) (C++ scenario)
  3. To implement callbacks

Example for Usage-1

#include<stdio.h>

float addition (float a, float b) {
 return a + b;
}

float subtraction (float a, float b) {
 return a - b;
}

float multiplication (float a, float b) {
 return a * b;
}

void select (float a, float b, char opCode) {
float result;
switch(opCode)
{
 case '+': result = addition(a, b); break;
 case '-': result = subtraction(a, b); break;
 case '*': result = multiplication (a, b); break;
}
printf("Result: %f\n", result);
}

/* Replace the above switch statement with function pointer */
void select_function_pointer (float a, float b, float (*math_pointer)(float, float)) {
float result = math_pointer(a, b); /* Calling function using function pointer */
printf("Result: %f\n", result);
}

void main()
{
  float a, b;
   
  select(10, 15, '+');
  select_function_pointer (10, 15, &addition); /* Passing function as an address argument */
}


Array of Function Pointers

Since the Function pointer is a variable, we can define array of function pointer using below syntax.


Syntax-I
tyepdef <data_type> function_pointer_name (argument data_type list);
function_pointer_name array_fun_pointer [10] = {NULL};

Syntax-II
<data_type> (*array_fun_pointer[10])(argument data_type list) = {NULL};

array_fun_pointer [0] = &function1;
.
.
Calling function using function pointer
(*array_fun_pointer[0]) (arguments); or
array_fun_pointer[0](arguments);


Implementation of Callbacks using Function Pointers

It is a bit more complex syntax. Try to understand the callback mechanism in C by using below sample code:

void insert_array (int *array, size_t size, int (*getNextValue) (void))
{
     for (int i = 0; i < size; i++)
        array[i] = getNextValue();
}

int getNextRandomValue()
{
   return rand();
}

int main()
{
   int a[10];
   insert_array(a, 10, &getNextRandomValue);
}

Here, the function insert_array() takes the 3rd argument as the function address using function pointer getNextValue. And, the callback function is getNextRandomValue(), returns random value. The function insert_array() calls this callback function using function pointer getNextValue for inserting the values into the array.

The similar explanation can be found here (from Stackoverflow)

Monday 2 December 2013

Tasklet Vs Work queues [Part-II]

For Tasklet Vs Work queues [Part-I], please click here.

Work queues

Work queues are added in linux kernel 2.6 version. And, one major difference between Work queues and Tasklets is that the handler function of work queues can sleep but not possible in the case of Tasklet's handler function.

Another difference is that the Work queues have higher latency than Tasklet.

We should look at two main data structures in the Work queue mechanism.
  1. struct workqueue_struct
  2. struct work_struct
The core work queue is represented by structure struct workqueue_struct, which is the structure onto which work is placed. This work is added to queue in the top half (Interrupt context) and execution of this work happened in the bottom half (Kernel context).

The work is represented by structure struct work_struct, which identifies the work and the deferral function.

Kernel threads named "events/X" will extract work from the core work queue and activates the work's handler function.

Work queue APIs

Create and destroy work queue structure

struct workqueue_struct *create_workqueue(name); /* Creates core workqueue */
void destroy_workqueue(struct workqueue_struct *); /* Destroy the workqueue */

Initialization of work structure

Work queue API provides 3 macros which initializes the work and also set the function handler.

INIT_WORK(work, function);
INIT_DELAYED_WORK(work, function); /* if we add any delay before adding this work into work queue structure */
INIT_DELAYED_WORK_DEFERRABLE(work, function);

EnQueue work on to work queue

Below are work queue APIs used for adding queue on to work queue.

int queue_work (struct workqueue_struct *wq, struct work_struct *work);
int queue_work_on (int cpu, struct workqueue_struct *wq, struct work_struct *work); /*  specify the CPU on which the handler should run */
int queue_delayed_work (struct workqueue_struct *wq, struct delayed_work *work), unsigned long delay); /* Queue specified work on to specified work queue after delay */
int queue_delayed_work_on (int cpu, struct workqueue_struct *wq, struct delayed_work *work), unsigned long delay);

The below functions doesn't require workqueue structure defined. These functions uses kernel-global work queue. So, no need to pass workqueue_struct in the argument list.

int schedule_work (struct work_struct *):
int schedule_work_on (int cpu, struct work_struct *):
int scheduled_delayed_work (struct delayed_work *, unsigned long delay);
int scheduled_delayed_work_on (int cpu, struct delayed_work *, unsigned long delay);

Cancel work

/* terminate work in the queue, which is not already executing in the handler */
int cancel_work_sync (struct work_struct *); 
int cancel_delayed_work_sync (struct delayed_work *);

Flush work

Below functions are used to flush the work and works in the specified workqueue.
/* Flush a particular work and block until it is completed */
int flush_work (struct work_struct *);
/* Flush all works in given workqueue and block until it is completed */
int flush_workqueue (struct workqueue_struct *);
/* Flush  kernel-global work queue */
void flush_scheduled_work (void);

Status of work

We can use below two functions to know whether the given work is pending i.e. its handler function is not yet started.
work_pending(work);
delayed_work_pending (work);

Next: Will share running examples for Tasklet and work queues.

Thursday 28 November 2013

Tasklets Vs Work queues in the kernel

Tasklets Vs Work queues in the kernel

Tasklets and work queues used to implement deferrable functionality in the kernel. Using the Tasklets and Work queues, we can schedule a function to run at later point of time.

Deferrable functions:

It is a mechanism for supporting delayed execution of functions (not urgent functions), used in interrupt handlers.
Types of deferrable functions
1.       Tasklets
2.       Work queues
Mostly, we use these functions in Interrupt Handlers. Because some or majority of the interrupts are disabled in interrupt context. So, if the functions take more time for execution in this context then the latency to handle other hardware interrupts. Generally, we enter into interrupt context when a hardware interrupt is raised.
If we add Deferrable function in the interrupt handlers then this function will be executed in Kernel Context where the all hardware interrupts are in enable mode. So, we move function of code which can later be executed without any harm using deferrable function. And, hence we are minimizing the latency to handle hardware interrupts.
Generally the processing of work done in interrupt handler called as Top Half.
And, the processing of work done in kernel context called as Bottom Half.
Aim: Reduce work (execution time of handler code) in Top Half
We can achieve this using Tasklets method or Work queue.

Using Tasklets:

As already mentioned, the main job of the Tasklets is to schedule the work (function) to run later point of time so that we can decrease the amount of work done in interrupt handlers.

/* Declaring Tasklet */

void tasklet_function(unsigned long data);
DECLARE_TASKLET(tasklet_name, tasklet_function, tasklet_data);

/* Scheduling Tasklet */

tasklet_schedule(&tasklet_name);

Tasklets are represented by tasklet_struct structure.
struct tasklet_struct {
                struct tasklet_struct *next; /*pointing to next tasklet structure */
                unsigned long state; /* state = TASKLET_STATE_SCHED or TASKLET_STATE_RUN */
                atomic count; /* 0 = Enable; !0 = Disable */
unsigned long data;
void (*func) (unsigned long); /*func(data) */
}
Tasklets are defined using a macro DECLARE _TASKLET, which initializes the tasklet_struct using its arguments tasklet_name, tasklet_func and data.
Tasklets are enabled by default when defined using DECLARE_TASKLET macro, so that we can schedule it directly without using any other APIs.
But, if we declare tasklet using DECLARE_TASKLET_DISABLED macro then we should explicitly call tasklet_enable() API before scheduling this tasklet.

Tasklet APIs:

/* Defining Tasklet using macros */
DECLARE_TASKLET(name, func, data);
DECLARE_TASKLET_DISABLED(name, func, data);

void tasklet_init(struct tasklet_struct *, void (*func) (unsigned long), unsigned long data); /*initializes the tasklet structure with user provided info */


/* Enabling and Disabling a tasklet using enable() and disable() */
void tasklet_enable(struct tasklet_struct *); /* Enable normal priority scheduling */
void tasklet_disable(struct tasklet_struct *); /* returns after disabling the tasklet */
void tasklet_hi_enable(struct tasklet_struct *); /* Enabling High priority scheduling */
void tasklet_disable_nosync(struct tasklet_struct *); /* may returns before termination */


/* Schedule a tasklet*/
void tasklet_schedule (struct tasklet_struct *); /* Normal priority scheduling */
void tasklet_hi_schedule (struct tasklet_struct *); /* Higher priority scheduling */


CPU maintains the normal and high priority softirq vectors lists (normal priority vector list and high priority vector list) where these functions are queued.
If the function is higher priority function then it is enqueued in higher priority softirq vector list and similar case for normal priority functions.


The below two functions are used to kill a tasklet
void tasklet_kill(struct tasklet_struct *);
void tasklet_hi_kill(struct tasklet_struct *); /* Kill the tasklet and ensure they would never run */

Sample Program: tasklet.c

#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/interrupt.h>
char tasklet_data[] = "tasklet function was called";
void my_tasklet_function (unsigned long data) {
        printk("%s: in %s\n", (char*)data, __func__);
}
DECLARE_TASKLET(my_first_tasklet, my_tasklet_function, (unsigned long)&tasklet_data);
int init_module()
{
        /* schedule our my_tasklet_function */
        tasklet_schedule(&my_first_tasklet);
        return 0;
}
void cleanup_module(void)
{
        tasklet_kill(&my_first_tasklet);
        return;
}

Makefile:

obj-m += tasklet.o
KDIR = /usr/src/linux-headers-2.6.32-28-generic
all:
        $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
clean:
        rm -rf *.o *.ko *.mod.* *.symvers *.order

Execution:

sudo insmod tasklet.ko

Output: dmesg


[3302661.097630] tasklet function was called: in my_tasklet_function

Next: Will cover work queues also...

Saturday 23 November 2013

[C programming] Storage classes in C

Storage classes in C

C supports four different storage classes. These are auto, register, static and extern storage classes.

C compiler automatically assigns auto storage class when we declare a variable without any storage class.

<syntax of storage class in c>

<storage_class> <data_type> <variable_name>;


<storage_class> gives the information about where the variable is stored in memory, default initial value, scope of the variable and it’s life time.

AutoRegisterStaticExtern
Default storage class.
int variable;
/*Above Declaration is same as below one */
auto int variable;
/*Declaration*/
register int variable;
/*Declaration*/
static int variable;
/* Declaration */
extern int variable;
Stored in stack memoryStored in CPU registersStored in Data segmentStored in Data segment
Default initial value: Contains garbage value by default.Default initial value: Contains garbage value by default.Default initial value: Default initial value of variable is 0Default initial value: Default initial value of variable is 0
Scope: local to the functionScope: local to the functionScope: local to the functionScope: visible to the outside of the file.
Value of variable persists in function.Value of variable persists in function.Value of variable persists between function callsVariable can be shared between multiple files
Lifetime: Variable is de-allocated when the function (where the variable is declared) execution is overLifetime: Variable is de-allocated when the function execution is overLifetime: Variable is de-allocated when the program is terminated after completion of job. So, lifetime doesn’t dependent on function execution.Lifetime: Variable is de-allocated when the program is terminated after completion of job.

Extern variable vs Global variable:

The scope of the global variable is limited to the file where it is declared. But, in case of extern variable, it can be shared among functions. So, variable visibility is more compared to global variable.

Both global and extern variables are stored in data segment and have default initial value is 0.

References:


Saturday 9 November 2013

What is Google ?

Today, I read a article "What Makes Google Services Work So Fast ?" at googlersays.com. This articles reveals something new and interesting facts about Google and its services.

We know that Google services are very fast, reliable, robust and trustworthy. We store our confidential information in Google services like Docs, gmail etc.

Google uses proprietary software which keeps its services at No.1 position.

Google File System: Google uses its own file system named as GFS (Google File System), provides reliable and efficient access to data.

Chubby: Google developed a lock services called Chubby, used for Shared resource management system. Heavily used as Domain Name Server.

BigTable: Google uses a Non-Relational Database called BigTable

Google also uses a OpenSource software for processing data

MapReduce: is s/w framework for processing large amount of unstructured data.

Linux Operating System: Majority of the Google servers/computers runs with Linux OS.

Please read the article What Makes Google Services Work So Fast ? for more details.


Thursday 7 November 2013

[C Programming] Check if two strings are anagrams

Anagram: Two strings S1 and S2 are called anagrams when string S2 can be formed if we rearrange the letters in string S1 and vice-versa.


Example: S1 = god, S2 = dog

Solution:
------------
If we apply XOR property here then we can easily find the given strings are anagrams or not.

1 XOR 1 = 0
1 XOR 0 = 1
a XOR z = 1
s XOR s = 0

If Inputs to the XOR operator are equal then result would be ZERO.

Apply XOR for each alphabet in both strings. If the result is ZERO then the strings are anagrams else not anagrams. It may not be sufficient condition since the strings "aaa" and "bbb" are not anagrams but still the XOR of these two strings is ZERO. Hence, one more check was needed to eliminate these usecases. Compute the sum of ascii value of two strings and check if they are equal. If equal then the two given strings are anagrams.

Sample code (anagram_string.c):
--------------------------------------
  #include<stdio.h>
  #include<string.h>

  void main(int argc, char *argv[])
  {
          char *str1, *str2;
          int xor, i;
          int sum1 = 0, sum2 = 0;


          if ( argc != 3 ) /* argc should be 3 for correct execution */
          {
                  /* argv[0] is the program name */
                  printf( "usage: %s string1 string2\n", argv[0] );
                  return;
          }

          str1 = argv[1];
          str2 = argv[2];

          printf("Entered strings \"%s\" and \"%s\"\n", str1, str2);

          if (strlen(str1) != strlen(str2)) {
                  printf("Given Strings are not anagrams\n");
                  return;
          }

          for (i = 0; i < strlen(str1); i++) {
                  xor ^= str1[i];
                  xor ^= str2[i];
                  sum1 += str1[i];
                  sum2 += str2[i];
          }

          if (!xor && (sum1 == sum2))
                  printf("Given Strings are anagrams\n");
          else
                  printf("Given Strings are not anagrams\n");

  }

Output:
======
gcc anagram_string.c
./a.out ram arm

Entered strings "ram" and "arm"
Given Strings are anagrams

Wednesday 6 November 2013

[C programming] Reverse an array in place (Do not use additional array)

Reverse an array in-place i.e you cannot use any additional array or
in other words, space complexity of the solution should be O(1)

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

void main()
{
int size, i, temp;
int *array;

printf("Enter size of an array:\n");
scanf("%d", &size);

array = (int*)malloc(sizeof(int) * size);

printf("Enter %d elements\n", size);
for (i = 0; i < size; i++)
scanf("%d", &array[i]);

printf("List elements are..\n");
for (i = 0; i < size; i++)
printf("%d\n", array[i]);

for (i = 0; i <= (size - 1) / 2; i++) {
temp = array[i];
array[i] = array[size-1-i];
array[size-1-i] = temp;
}

printf("After Reversing the list,  elements are..\n");
for (i = 0; i < size; i++)
printf("%d\n", array[i]);
}

Tuesday 5 November 2013

[Ubuntu] How to use ctags

ctags with vim editor are very helpful for code walk-through. Navigation is very easy in the large code bases like kernel, where we can jump to
function/identifier definition directly using simple keys.

ctags installation:
=============
ctags can be installed in ubuntu by

sudo apt-get install exuberant-ctags

How to use ctags:
==============

1. Generate tag file for the required code base.

change your current working directory to desired code base directory using cd command.
Now, run below command

ctages -R .

Output: We see "tags" file in the current working directory after successful.
It will store all index information of functions or identifiers in the tag file.

2. Now, open any file in the current working directory using vim editor.
   Place cursor on any funtion/identifier.

3. Press ctrl + ] together. We will redirect to the file where this function/identifier is defined.

If there are multiple entries for this definition, we can check one by one by following way

Goto vim's command mode by typing ":" and type tnext (goes to next tag)

4. Once you see the required definition, use ctrl+t to go back to your base point where you did step-3


Note: Instead of step-2, we can use vim’s command mode to jump to function/identifier definition:

:tag function_name
:ta function_name

The below commands will be used to accept regular expressions.

Example, :tag /^asserts_* would find all tags that start with ‘asserts_’.
By default vim will jump to the first result, but a number of commands can be used to sort through the list of tags:

:ts or :tselect shows the list
:tn or :tnext goes to the next tag in that list
:tp or :tprev goes to the previous tag in that list
:tf or :tfirst goes to the first tag of the list
:tl or :tlast goes to the last tag of the list
To show the tags you’ve traversed since you opened vim, run :tags.

For more info on ctags, please check here

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


You might also like

Related Posts Plugin for WordPress, Blogger...