17 Dec 2017

Why function pointer is used in C language?

What is function Pointer?
->funtion pointer is pointer that holds the address of a function.
Why function pointers are used in C?
->function pointers are mainly used to implement callback functions.
What is callback function in C?
->callback functions are functions which are passed as argument to other functions and this passed callback function is invoked on some event.

->best example is sigaction system call. When given event/signal like alarm,SIGINT occurs,the function pointed by the pointer  is called through the function pointer in sigaction structure.example B

->another use of function pointer is generality like templates in c++.ie. with the same function pointer different
functions can be called.example A below.

/*Example A:
 same function pointer is used to call add and sub function*/
#include<stdio.h>
/*prototype here: funcPtr is function pointer taking two integers as arguments and returning an int
int (*funcPtr(int, int))
*/
/*prototype of registration function generally used to pass function pointer as argument*/
int regfunc(int (*funcPtr)(int, int), int,  int);
/*proto types of function called by function pointers*/
int add(int a, int b);
int sub(int a, int b);

/*definition of first function called through function pointer*/
int add(int a, int b)
{
        return a+b;
}
/*definition of second function called through function pointer*/
int sub(int a, int b)
{
        return b-a;
}
/*main for calling functions through function pointer */
int main()
{
        int a,b;
        a=regfunc(add,10,20);
        printf("sum is %d\n",a);

        b=regfunc(sub,10,20);
        printf("sub is %d\n",b);

        return 0;
}
/*definition of registration function that receives a funcPtr and two inta*/
int regfunc(int (*funcPtr)(int x,int y),  int x,  int y)
{
        return (*funcPtr)(x,y);
}
/*
sum is 30
sub is 10
*/

/*Example B:
->best example is sigaction system call. When given event/signal like alarm,SIGINT occurs,
the function pointed by the pointer act is called though the function pointer in sigaction structure.example B
*/
/*
struct sigaction
{
void (*sa_handler)()//address of sighandler or SIG_IGN or SIG_DEF
sigset_t sa_mask;//to block other signals
int sa_flags;
};
*/


/*
function pointer are reference to code that are passed as argument to different code. callback functions are function which are invoked on some event.
*/
#include<stdio.h>
#include<signal.h>
#include<unistd.h>


struct sigaction act;
/*call back function to be called by funcptr on alarm event*/
void sig_handler(int signo, siginfo_t *si, void *ucontext)
{
printf("Alarm signal received is:%d\n",signo);
}

int main()
{
/*intializig function pointer with func1*/
act.sa_handler=sig_handler;
act.sa_flags=SA_SIGINFO;
/*registering functon pointer to register function*/
/*ie passing functon pointer as argument to register function*/

/*Alarm event will cause call back function call through function pointer pointed by ptr act */
sigaction(SIGALRM,&act,NULL);

alarm(3);/*Now Alarm event will cause call back function call through function pointer pointed by ptr act */

/*waiting for any signal from kernel*/
pause();

/*after signal handler call back function executed*/
printf("in main again\n");
        return 0;
}

/*
Alarm signal received is:14
in main again
*/


/*
function pointer are reference to code that are passed as argument to different code. callback functions are function which are invoked on some event.
*/
#include<stdio.h>

typedef void (*funcPtr)(void);
void regfuncPtr(funcPtr myfp);
void func1();

int main()
{
/*intializig function pointer with func1*/
        funcPtr myfp=func1;
/*registering functon pointer to register function*/
/*ie passing functon pointer as argument to register function*/
        regfuncPtr(myfp);

        return 0;
}
/*defintion of register function*/
void regfuncPtr(funcPtr myfp)
{
        printf("inside regFuncPtr\n");
        (*myfp)();
}
/*definition of function to be called by function pointer*/
void func1()
{
        printf("inside func1\n");
}
/*
inside regFuncPtr
inside func1

*/

/*What is function pointer in C?
functon pointer are reference to code that are passed as argument to different code.
What is callback function in C?
callback functions are function which are invoked on some event.
*/
#include<stdio.h>
#include<signal.h>
#include<unistd.h>


/*Another example of call back function to be called by funcptr on alarm event in C language*/
void mysignalHandler(int signo)
{
printf("\n mysignalHAndler: Alarm signal received is:%d\n",signo);
}

int main()
{
signal(SIGINT,mysignalHandler);
/*create some delay*/
printf("sleeping for 10 seconds.\n");
printf("generate SIGINT by ctrl+c command: else normal exit\n");
sleep(10);

/*after signal handler call back function executed*/
printf("in main again\n");
        return 0;
}

/*
Alarm signal received is:14
in main again
*/
This page explained syntax and c linux code for :
pointer to function
function pointer
callback functions

POSIX Semaphore Implementation Example code in C on Linux

POSIX semaphore Implementation for thread synchronization.

Accept string and convert its case. If semaphore is not used chances are there that input of one thread gets converted by other thread and unwanted result.

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<string.h>

#define MAXMSGLEN 256

sem_t sem1;
char msg1[MAXMSGLEN];
char msg2[MAXMSGLEN];
sem_t sem2;

void* threadFunc1(void *arg);
void toggleCase(char *buf);

int main()
{
        pthread_t thread1;
        char argmsg1[]="Thread1: ";
        int res;
        int thNum;

        res=sem_init(&sem1,0,0);
        res=sem_init(&sem2,0,0);

        res=pthread_create(&thread1,NULL,threadFunc1,argmsg1);

        while(1)
        {
                printf("Print message to send:\n");
                fgets(msg1,MAXMSGLEN,stdin);
                sem_post(&sem1);
                /******wait for response****/
                sem_wait(&sem2);
                printf("Resp message: %s \n",msg2);
        }
        return 0;
}
void* threadFunc1(void *arg)
{
        printf("I am :%s \n",arg);
        while(1)
        {
                sem_wait(&sem1);
                strcpy(msg2,msg1);
                toggleCase(msg2);
                sem_post(&sem2);
        }
}
void toggleCase(char *str)
{
        while(*str)
        {
                if(isupper(*str))
                        *str=tolower(*str);
                else if(islower(*str))
                        *str=toupper(*str);
                str++;
        }
}
output:
   Print message to send:
   I am :Thread1:
   aaaaa
   Resp message: AAAAA
Print message to send:
   bbbbb
   Resp message: BBBBB

   Print message to send:
   CCCCC
   Resp message: ccccc

   Print message to send:
   asdfZXCV
   Resp message: ASDFzxcv

   Print message to send:

   WITHOUT sem OP is:
   -----------------=-
   Print message to send:
   I am :Thread1:
   qqqqqqqq
   Resp message:
   Print message to send:
   aaaa
   Resp message: QQQQQQqq

   Print message to send:
   ddd
   Resp message: AAAa

   Print message to send:
   aaaa
   Resp message: ddd

   Print message to send:
   ---------------------

POSIX Mutex Implementation C Program in Linux

POSIX MUTEX implementationstwo threads takes 2 strings and combined.Two thrads trying to read two strings from the user and combined it.If mutex not used then it may be that second string  may be read by other thread.Here, with mutex we are sharing the keyboard effectively.Mutex here ensures that which ever thread gets the mutex lock will read the both strings from the user keyboard.

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
pthread_mutex_t mlock;
pthread_t th1;
void *threadFunc1(void *arg);
int main()
{
        char str1[80];
        char str2[40];
        if(pthread_mutex_init(&mlock,NULL)!=0)
        {
                printf("Mutext creation failed,\n");
                exit(1);
        }
        pthread_create(&th1,NULL,threadFunc1,NULL);
        while(1)
        {
                pthread_mutex_lock(&mlock);
                printf("MAIN THREAD Enter 2 strings:\n");
                fgets(str1,40,stdin);
                fgets(str2,40,stdin);
                strcat(str1,str2);
                printf("In main Combined String is:%s\n",str1);
                        pthread_mutex_unlock(&mlock);
        }
        return 0;
}
void* threadFunc1(void *arg)
{
        char str1[80];
        char str2[80];
        while(1)
{
pthread_mutex_lock(&mlock);
        printf("thread function Enter 2 strings:\n");
        fgets(str1,40,stdin);
        fgets(str2,40,stdin);
        strcat(str1,str2);
        printf("In Thread function Combined String is:%s\n",str1);
                pthread_mutex_unlock(&mlock);
}
}
........................................................................................................................................
MAIN THREAD Enter 2 strings:
aaaa
bbbbb
In main Combined String is:aaaa
bbbbb

MAIN THREAD Enter 2 strings:
ssss sss
dddd
In main Combined String is:ssss sss
dddd

thread function Enter 2 strings:
gggg gggg
fff fff
In Thread function Combined String is:gggg gggg
fff fff

MAIN THREAD Enter 2 strings:
sdfg
hhhhj
In main Combined String is:sdfg
hhhhj

MAIN THREAD Enter 2 strings:

7 Dec 2017

Singleton Design Pattern


Intent
The Singleton pattern ensures a class has only one instance, and provides a global point of access to it.

singleton
A Singleton is an elegant way of maintaining global state, but we should always question whether we need global state. Singleton pattern offers several advantages over global variables because it does the following:
  1. Enforces that only one instance of the class can be instantiated.
  2. Allows control over the allocation and destruction of the object.
  3. Provides thread-safe access to the object's global state.
  4. Prevents the global namespace from being polluting.
Let's think about a class which has private constructor.
It becomes a class that can't be instantiated because it has private constructor.
class MyClass {
private:
 MyClass(){}
};
We need to have an instance of the class to call it, but we can't have an instance because no other class can't instantiate it. We can use the constructor from an object of type MyClass but we can never instantiate that object because no other object can use:
new MyClass();
So, we should find a way of using a static method.
Here is an example code:
#include <iostream>

using namespace std;

class Singleton
{
public:
 static Singleton *getInstance(); 

private:
 Singleton(){}
 static Singleton* instance;
};

Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance() 
{
 if(!instance) {
  instance = new Singleton();
  cout << "getInstance(): First instance\n";
  return instance;
 }
 else {
  cout << "getInstance(): previous instance\n";
  return instance;
 }
}

int main()
{
 Singleton *s1 = Singleton::getInstance();
 Singleton *s2 = Singleton::getInstance();
 return 0;
}

Output from the run:
getInstance(): First instance
getInstance(): previous instance

Singleton pattern limits the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.


We can modify the design of the code with the following constraints:
  1. We do not want the singleton by copied so that there is only one instance. This can be achieved by declaring a private copy constructor and a private assignment operator.
  2. The getInstance() method should return a reference rather than a pointer. This blocks a client from deleting the object. Also, by making destructor private, we can achieve the same effect.
The revised code looks like this:
#include <iostream>

class Singleton
{
public:
 static Singleton& getInstance(); 

private:
 Singleton() {std::cout << "Ctor\n";};
 ~Singleton() {std::cout << "Dtor\n";};
 Singleton(const Singleton&);
 const Singleton& operator=(const Singleton&);
};

Singleton& Singleton::getInstance() 
{
 static Singleton instance;
 return instance;
}

int main()
{
 Singleton &s1; = Singleton::getInstance();
 Singleton &s2; = Singleton::getInstance();
 return 0;
}


Thread Safe Singleton
The revised version is not thread safe because there could be a race condition during the initialization of the static Singleton, Singleton& Singleton::getInstance(). But we can make the method thread safe by adding a mutex lock:
Singleton& Singleton::getInstance() 
{
        Mutex mutex;
        ScopedLock(&mutex;);  // to unlock mutex on exit
 static Singleton instance;
 return instance;
}



Notes
In 2009, the authors of the original design patterns said the only pattern they would consider removing from the original list is Singleton. This is because it is essentially a way to store global data and tends to be an indicator of poor design.
There are several alternatives to the Singleton pattern:

  1. dependency injection
  2. Monostate pattern
  3. session context

7 Nov 2017

TASK ON LINUX (FORK SYSTEM CALL)

1) Write a program to create 3 child process. All child processes should create from the single parent not nested into another child process. Each child process prints its PID and random counter with random intervals(Ex: when child 1 starts running then it first print its PID and it starts printing random counter from zero to counter value with random delays and finally exit to the main process. ).The main process should wait until all child processes complete their work.

19 Sept 2017

Namespace in c++

Consider following C++ program.
// A program to demonstrate need of namespace
int main()
{
    int value;
    value = 0;
    double value; // Error here
    value = 0.0;
}Output :
Compiler Error:
'value' has a previous declaration as 'int value'
In each scope, a name can only represent one entity. So, there cannot be two variables with the same name in the same scope. Using namespaces, we can create two variables or member functions having the same name.
// Here we can see that more than one variables
// are being used without reporting any error.
// That is because they are declared in the
// different namespaces and scopes.
#include <iostream>
using namespace std;
// Variable created inside namespace
namespace first
{
    int val = 500;
}
// Global variable
int val = 100;
int main()
{
    // Local variable
    int val = 200;
    // These variables can be accessed from
    // outside the namespace using the scope
    // operator ::
    cout << first::val << '\n';
    return 0;
}Output:
500

Definition and Creation:

Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names.
  • Namespace is a feature added in C++ and not present in C.
  • A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc) inside it.
  • Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name 
{
   int x, y; // code declarations where 
             // x and y are declared in 
             // namespace_name's scope
}
  • Namespace declarations appear only at global scope.
  • Namespace declarations can be nested within another namespace.
  • Namespace declarations don’t have access specifiers. (Public or private)
  • No need to give semicolon after the closing brace of definition of namespace.
  • We can split the definition of namespace over several units.
// Creating namespaces
#include <iostream>
using namespace std;
namespace ns1
{
    int value()    { return 5; }
}
namespace ns2
{
    const double x = 100;
    double value() {  return 2*x; }
}
int main()
{
    // Access value function within ns1
    cout << ns1::value() << '\n';
    // Access value function within ns2
    cout << ns2::value() << '\n';
    // Access variable x directly
    cout << ns2::x << '\n';      
    return 0;
}Output:
5
200
100

Classes and Namespace:

Following is a simple way to create classes in a name space
// A C++ program to demonstrate use of class
// in a namespace
#include <iostream>
using namespace std;
namespace ns
{
    // A Class in a namespace
    class geek
    {
    public:
        void display()
        {
            cout << "ns::geek::display()\n";
        }
    };
}
int main()
{
    // Creating Object of student Class
    ns::geek obj;
    obj.display();
    return 0;
}Output:
ns::geek::display()
Class can also be declared inside namespace and defined outside namespace using the following syntax
// A C++ program to demonstrate use of class
// in a namespace
#include <iostream>
using namespace std;
namespace ns
{
    // Only declaring class here
    class geek;
}
// Defining class outside
class ns::geek
{
public:
    void display()
    {
        cout << "ns::geek::display()\n";
    }
};
int main()
{
    //Creating Object of student Class
    ns::geek obj;
    obj.display();
    return 0;
}Output:
ns::geek::display()
We can define methods also outside the namespace. Following is an example code.
// A C++ code to demonstrate that we can define
// methods outside namespace.
#include <iostream>
using namespace std;
// Creating a namespace
namespace ns
{
    void display();
    class geek
    {
    public:
       void display();
    };
}
// Defining methods of namespace
void ns::geek::display()
{
    cout << "ns::geek::display()\n";
}
void ns::display()
{
    cout << "ns::display()\n";
}
// Driver code
int main()
{
    ns::geek obj;
    ns::display();
    obj.display();
    return 0;
}Output:
ns::display()
ns::geek::display()

Extending namespace and Unnamed namespace

It is also possible to create more than one namespaces in the global space. This can be done in two ways.
  • namespaces having different names
    // A C++ program to show more than one namespaces
    // with different names.
    #include <iostream>
    using namespace std;
    // first name space
    namespace first
    {
       int func() {  return 5; }
    }
    // second name space
    namespace second
    {
       int func() { return 10; }
    }
    int main()
    {
       // member function of namespace
       // accessed using scope resolution operator
       cout << first::func() <<"\n";       
       cout << second::func() <<"\n";
       return 0;
    }Output:
    5
    10
    
  • Extending namespaces (Using same name twice)
    It is also possible to create two namespace blocks having the same name. The second namespace block is nothing but actually the continuation of the first namespace. In simpler words, we can say that both the namespaces are not different but actually the same, which are being defined in parts.
    // C++ program to demonstrate namespace exntension
    #include <iostream>
    using namespace std;
    // first name space
    namespace first
    {
       int val1 = 500; 
    }
    // rest part of the first namespace
    namespace  first
    {
       int val2 = 501; 
    }
    int main()
    {
       cout << first::val1 <<"\n";       
       cout << first::val2 <<"\n";
       return 0;
    }Output:
    500
    501
    
Unnamed Namespaces
  • They are directly usable in the same program and are used for declaring unique identifiers.
  • In unnamed namespaces, name of the namespace in not mentioned in the declaration of namespace.
  • The name of the namespace is uniquely generated by the compiler.
  • The unnamed namespaces you have created will only be accessible within the file you created it in.
  • Unnamed namespaces are the replacement for the static declaration of variables.
// C++ program to demonstrate working of unnamed
// namespaces
#include <iostream>
using namespace std;
// unnamed namespace declaration
namespace
{
   int rel = 300;
}
int main()
{
   cout << rel << "\n"; // prints 300
   return 0;
}Output:
300