Showing posts with label C Linux Code. Show all posts
Showing posts with label C Linux Code. Show all posts

Synchronized shared memory server and client in C

Client writes  a text in shared memory.
Then server reads that and convert to upper case and write back to shared memory.
Client reads toggled text from shared memory.
//Server
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>

#define MY_KEY 1983
#define SHM_SIZE 0x1000

void toggleCase(char* buff, int cnt);

int main()
{
int semId, shmId;
char* pShm;
struct sembuf smop;

semId=semget(MY_KEY,2,0660 | IPC_CREAT);

semctl(semId,0,SETVAL,0);
semctl(semId,1,SETVAL,0);
shmId = shmget(MY_KEY, SHM_SIZE, 0660 | IPC_CREAT);

pShm=shmat(shmId,NULL,0);

while(1)
{
smop.sem_num = 0;
smop.sem_op = -1;
smop.sem_flg = 0;
semop(semId,&smop,1);

strcpy(pShm+256,pShm);
toggleCase(pShm+256, strlen(pShm+256));

smop.sem_num = 1;
smop.sem_op = 1;
smop.sem_flg = 0;
semop(semId,&smop,1);

}
return 0;
}

void toggleCase(char* buff, int cnt)
{
printf("\ntoggle\n");
int ii;
for(ii=0;ii<cnt;ii++)
{
if((buff[ii]>='A')&&(buff[ii]<='Z'))
buff[ii]+=0x20;
else if((buff[ii]>='a')&&(buff[ii]<='z'))
buff[ii]-=0x20;
}
}

//Client
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>

#define MY_KEY 1983
#define SHM_SIZE 0x1000

#define MSG_LEN 256
#define RESP_MSG_START 256

//void toggleCase(char* buff, int cnt);

int main()
{
int semId, shmId;
char* pShm;
struct sembuf smop;

semId=semget(MY_KEY,2,0);

//semctl(semId,0,SETVAL,0);
//semctl(semId,1,SETVAL,0);

shmId = shmget(MY_KEY, SHM_SIZE,0);

pShm=shmat(shmId,NULL,0);

fgets(pShm,MSG_LEN,stdin);

smop.sem_num = 0;
smop.sem_op = 1;
smop.sem_flg = 0;
semop(semId,&smop,1);

smop.sem_num = 1;
smop.sem_op = -1;
smop.sem_flg = 0;
semop(semId,&smop,1);
puts(pShm+RESP_MSG_START);
return 0;
}

//void toggleCase(char* buff, int cnt)
//{
//printf("\ntoggle\n");
//}

//terminal 1: ./server
//terminal 2: ./client
india
check
//terminal 1: 
//terminal 2:
INDIA  

make and makefile interview questions

Source code can be found here .
 Just download or clone and build by running command "make".
Q)What is make?
->make is a build automation tool that automatically build executables and libraries by reading a file called Makefile which tells the make how to compile and link a program.
Q)What is a makefile?
Makefile is the recipe(rule to build) file, which tells the build automation tool "make" how to compile and link.
Q)What does a makefile contains?
A makefile mainly contains directives(rules) like target,dependency and and rule. It also contains "set" directive to set a variable and comments, statements stating with a #.
Syntax of a makefile:
target: dependencies
[ a tab ]recipe (system commands)

Where: target, is name of the executable(binary),object file or any action like "clean".
dependency, is the input files required to create the binary and
recipe, are the system commands that make carries out.
Q)What is the difference between makefile and Makefile?
Order of execution is the difference.
If for execution "make" is not given "-f" option then it first looks for a file "makefile" then "Makefile".
If for execution "make" is given "-f" option then it first looks for a file "Makefile" then "makefile".

A simple example of makefile:
hello: main.o factorial.o hello.o
g++ main.o factorial.o hello.o -o hello
main.o: main.cpp functions.h
g++ -c main.cpp
factorial.o: factorial.cpp functions.h
g++ -c factorial.cpp
hello.o: hello.cpp functions.h
g++ -c hello.cpp
clean:
-rm *.o
---------------------------
code:
//main.cpp
#include <iostream>
using namespace std;
#include "functions.h"

int main(){
   print_hello();
   cout << endl;
   cout << "The factorial of 5 is " << factorial(5) << endl;
   return 0;
}

//functions.h
void print_hello();
int factorial(int n);

//functions.cpp
#include "functions.h"
int factorial(int n){
   if(n!=1){
      return(n * factorial(n-1));
   }
   else return 1;
}
//hello.cpp
#include <iostream>
using namespace std;
#include "functions.h"
void print_hello(){
   cout << "Hello World!";
}

CMakeLists.txt and cmake interview questions


Casting examples in C++ Linux


#include <QCoreApplication>
#include <iostream>
using namespace std;
class A
{
};
class B
{
};
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cout<<"Hello"<<endl;

    A *aa = new A;

//    B *bb = static_cast<B*>(aa);//Invalid cast A* to B*
//    B *bb = const_cast<B*>(aa);//Invalid cast A* to B*
//    B *bb = dynamic_cast<B*>(aa);//Invalid cast A* to B* source is not polymorphic
      B *bb = reinterpret_cast<B*>(aa);//OK
    return a.exec();
}
//---------------------------
#include <QCoreApplication>
#include <iostream>
using namespace std;
class A
{
public:
    virtual ~A(){}//making source A as polymorphic
};
class B
{

};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cout<<"Hello"<<endl;

    A *aa = new A;

//    B *bb = static_cast<B*>(aa);//Invalid cast A* to B*
//    B *bb = const_cast<B*>(aa);//Invalid cast A* to B*
      B *bb1 = dynamic_cast<B*>(aa);//Compiles ok but run time crash
      B *bb2 = reinterpret_cast<B*>(aa);//OK
    return a.exec();
}
//-----------------------------------------
#include <QCoreApplication>
#include <iostream>
using namespace std;
class A
{
};
class B:public A
{
};
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cout<<"Hello"<<endl;
    A *aa = new A;
    B *bb1 = static_cast<B*>(aa);//Ok
    //B *bb2 = const_cast<B*>(aa);//Invalid cast A* to B*
    //B *bb3 = dynamic_cast<B*>(aa);//Invalid cast A* to B*
    B *bb4 = reinterpret_cast<B*>(aa);//OK
    return a.exec();
}

//-----------------------------------------
#include <QCoreApplication>
#include <iostream>
using namespace std;
class A
{
public:
    virtual ~A(){}
};
class B:public A
{
};
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cout<<"Hello"<<endl;
    A *aa = new A;
    B *bb1 = static_cast<B*>(aa);//Ok
    //B *bb2 = const_cast<B*>(aa);//Invalid cast A* to B*
    B *bb3 = dynamic_cast<B*>(aa);//ok
    B *bb4 = reinterpret_cast<B*>(aa);//OK
    return a.exec();
}
//Dynamic Cast demos
Dynamic_cast is used for down casting  polymorphic base pointer to derived class poinetr to access member function defined by derived class in safe way.
#include <iostream>
#include <exception>
using namespace std;
class base { virtual void dummy() {} };
class derived: public base { int a; };
int main ()
 {
      try
            {
                base * pba = new derived;
                base * pbb = new base;
                derived * pd;
                pd = dynamic_cast<derived*>(pba);//d to b dynamic_cast ok
                              //because polymorphic base class elese run time error
                if (pd == 0)
                    cout << "Null pointer on first type-cast" << endl;
                pd = dynamic_cast<derived*>(pbb);
                if (pd == 0)
                    cout << "Null pointer on second type-cast" << endl;//gets printed
            }
            catch (exception& e)
            {
                cout << "Exception: " << e.what();
            }
            return 0;
        }
      
      #include <iostream>
        #include <typeinfo>
        using namespace std;
        int main ()
        {
            int * a;
            int b;
            a = 0; b = 0;
            if (typeid(a) != typeid(b))
            {
                cout << typeid(a).name()<<endl;//pi
                cout << typeid(b).name()<<endl;//i
            }
            return 0;
        }
Example Code:
        #include <iostream>
        #include <typeinfo>
        #include <exception>
        using namespace std;
        class base
        {
            virtual void f(){}
        };
        class derived : public base {};
        int main ()
        {
            try
            {
                base* a = new base;
                base* b = new derived;
                cout << typeid(*a).name() << '\n';//4base
                cout << typeid(*b).name()<<"\n";//7derived
            }
            catch (exception& e)
            {
                cout << "Exception: " << e.what() << endl;
            }
            return 0;
        }
Example Code:
        #include <typeinfo>
        #include <iostream>
        using namespace std;
        class A
        {
            public:
            virtual ~A();
        };
        int main()
        {
            A* a = NULL;
            try
            {
                cout << typeid(*a).name() << endl;
            }
            catch (bad_typeid)
            {
                cout << "Object is NULL" << endl;
            }
        }
Example Code:
        #include <iostream>
        using namespace std;
        struct A
        {
            virtual void f() 
            {
                cout << "Class A" << endl;
            }
        };
        struct B : A
        {
            virtual void f()
            {
                cout << "Class B" << endl;
            }
        };
        struct C : A
        {
            virtual void f()
            {
                cout << "Class C" << endl;
            }
        };
        void f(A* arg)
        {
            B* bp = dynamic_cast<B*>(arg);
            C* cp = dynamic_cast<C*>(arg);
            if (bp)
                bp -> f();
            else if (cp)
                cp -> f();
            else
                arg -> f(); 
        };
        int main()
        {
            A aobj;
            C cobj;
            A* ap = &cobj;
            A* ap2 = &aobj;
            f(ap);
            f(ap2);
        }
/*
class C
Class A
*/
Example Code:
#include<iostream>
using namespace std;
class Base
{
public:
virtual    void f(){cout<<"Base::f"<<endl;}
};
class Derive:public Base
{
public:
virtual     void f(){cout<<"Derived::f"<<endl;}
};
int main()
{
//CASE 1----------------------------------------------------------------
//Base *b = new Derive();
Base *pb;
Derive *pd;
//pb=pd;//No error
//pd=pb;error: invalid conversion from ‘Base*’ to ‘Derive*’

pb = dynamic_cast<Base*>(pd);
if(pd!=NULL)
{
cout<<"derive to base pass\n";
//pd->f();//run time crash
//pb->f();// run time rash
}
else if(pd==NULL)
{
cout<<"derive to base fail\n";
}
Base *b = new Derive();
Base *pb2;
Derive *pd2;
//pb2=pd2;//No error
//pd2=pb2;//error: invalid conversion from ‘Base*’ to ‘Derive*’

//CASE 2------------------------------------------------------------------
b = dynamic_cast<Base*>(pd2);
if(pd2!=NULL)
{
cout<<"derive to base pass2\n";
//pd2->f();//run time crash
//pb2->f();// run time rash
}
else if(pd2==NULL)
{
cout<<"derive to base fail2\n";
}
//CASE 3---------------------------------------------------------------
//Base *b = new Derive();
cout<<"31"<<endl;
Base *pb3;
cout<<"32"<<endl;
Derive *pd3;
cout<<"33"<<endl;
//pb=pd;//No error
//pd=pb;error: invalid conversion from ‘Base*’ to ‘Derive*’
/*
pd3 = dynamic_cast<Derive*>(pb3);//BOOOOM
cout<<"34"<<endl;
if(pb3!=NULL)
{
cout<<"base to derive pass 3\n";
}
else if(pb3==NULL)
{
cout<<"base to derive 3\n";
}
*/
//CASE 4-------------------------------------------------------------------
Base *b4 = new Derive();
//Base *pb4;
Derive *pd4;
pd4 = dynamic_cast<Derive*>(b4);//BOOM
cout<<"44"<<endl;
//if(pb4!=NULL)
//{
//cout<<"pb4 base to derive pass4\n";
//}
//else if(pb4==NULL)
//{
//cout<<"pb4 base to derive fail4\n";
//}

if(b4!=NULL)
{
cout<<"b4 base to derive pass4\n";
b4->f();//Derive::f
}
else if(b4==NULL)
{
cout<<"b4 base to derive fail4\n";
}
if(pd4!=NULL)
{
cout<<"pd4 base to derive pass4\n";
pd4->f();//Derive::f()
}
else if(pd4==NULL)
{
cout<<"pd4 base to derive fail4\n";
}
return 0;
}
Example Code:
#include<iostream>
using namespace std;
class Base
{
public:
    virtual void f(){cout<<"Base::f"<<endl;}
};
class Derive:public Base
{
public:
    virtual void f(){cout<<"iDerived::f"<<endl;}
};
int main()
{
Base *b = new Derived;
return 0;
}

        #include <iostream>
        using namespace std;
        struct A
        {
            virtual void f() 
            {
                cout << "Class A" << endl;
            }
        };
        struct B : A
        {
            virtual void f()
            {
                cout << "Class B" << endl;
            }
        };
        struct C : A
        {
            virtual void f()
            {
                cout << "Class C" << endl;
            }
        };
        void f(A* arg)//cobj the aobj
        {
            B* bp = dynamic_cast<B*>(arg);//cobj to bobj fails //arg2. aobj to bobj fails
            C* cp = dynamic_cast<C*>(arg);//cobj to cobj pass //arg2.  aobj to cobj fails

            if (bp)
        {
        cout<<"bp\n";
                bp -> f();
        }
            else if (cp)
        {
        cout<<"cp\n";
                cp -> f();
        }
            else
        {
        cout<<"else\n";
                arg -> f(); 
        }
        };
        int main()
        {
            A aobj;
            C cobj;
            A* ap = &cobj;
            f(ap); //Cp C

            A* ap2 = &aobj;
            f(ap2);//else A

        }
 

C++ reference FAQ interview questions

//1.References are nothing but constant pointer.
//2.So,references once initialized can not refer to other.
//2.1 Reference to reference not allowed.No error but. it will start pointing to the first variable
//3. reference arithmatic not allowed.No error in reference arithmatic but changes reflected in referant not in reference.
//4.Reference to array allowed.//int (&r)[5];
//5.Array of reference not allowed because we can not find the address of array. ultimately refer to first variable.
//6.Unlike pointers,refernce are automatically gets dereferenced.No need to use *(value at address).
//7.Unlike pointers, reference arithmatic like increment will increase the referant's value and not the address
//8.Reference are used to pass by reference to get the changes reflected in calling function.
//9.Pass by reference avoids copy of large value when structure like data are passed as arguments.
//10. Its unsafe to return local variable by value because variable goes out of scope once conrol returns out of the function defintion.
//Solution is us local static variable or dynamic memory allocation so that scope of the variable will through out the program.
#include<iostream>
using namespace std;
int gv;
int main()
{
//reference nothing but constant pointer means once initialized can not be reinitialized.
int s=10;
int *const h=&s;//s is const pointer so can not hold another address
//h=&m;//error: assignment of read-only variable ‘h’


int i=10,m=2;
int &j=i;// j is reference to a

//reference to refernce not allowed. No error but points to the first variable
int &k=j;//reference to reference no error but//point 2.1
k=20;
cout<<i<<endl;//20

//pointer arithmatic are not allowed. no error but changes gets reflected in first variable
k++;//point 7
cout<<i<<endl;//21

//referece can not be reinitialized but direct values can be given
int a=1;
k=1;
cout<<k<<endl;

//pass by reference to get the values reflected in calling function
int x=10,y=20;
swap(x,y);
cout<<x<<" " <<y<<endl;//20,10

//if return type is reference then function call can be made in left side
int &f();
f()=5;
cout<<"gv="<<gv<<endl;//5//instead of returned reference 100, f() is assigned to 5

//problem of local ovariable returning by value
int d;
int ff(d);
cout<<"d="<<d<<endl;//Garbage, because return value went out of scope in definition itself.
return 0;
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=x;
}
//return by reference
int &f()
{
gv=100;
return gv;
}
//problem of returning local variable by value
int ff(int t)
{
int& lv=t;
lv=lv+44;
return lv;//returning local variable by value.
}//scope of lv over here
You may also like.

Find and remove loop in linked list code in cpp linux

//Remove Loop in a linked list1.
//Find the loop and pass the loop node to removeLoop function.
//assign pointer ptr1=start.
//start infinite loop.
//assign pointer ptr2=loopnode.
//in loop traverse till ptr2->next!=loopnode && ptr2->next!=ptr1
//loop is found when ptr2->next=ptr1 ; break the loop
//else increment ptr1//most important
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
struct node *start=NULL;
//Inserting at start
void insert(struct node** ref,int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=(*ref);
*ref=newnode;//mind it
}
//displaying
void display(struct node *ref)
{
struct node *ptr=ref;
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->next;
}
printf("\n");
}
//Detecting Loop
void loopDetect()
{
struct node* slow=start;
struct node* fast=start;
while(start->next !=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
printf("LoopDetected\n");
removeLoop(slow);
break;//else infinite time LoopDetected gets printed
}
}
}
void removeLoop(struct node *loopnode)
{
printf("\nRemoveLoop Called.\n");
struct node *ptr1;
struct node *ptr2;
ptr1=start;
while(1)
{
ptr2=loopnode;
while(ptr2->next != loopnode && ptr2->next!=ptr1)
{
ptr2=ptr2->next;
}
if(ptr2->next==ptr1)//mind the next
break;
else
ptr1=ptr1->next;
}
ptr2->next=NULL;
}
int main()
{
insert(&start,10);
insert(&start,20);
insert(&start,30);
insert(&start,40);
insert(&start,50);
display(start);
//create a loop
start->next->next->next->next=start->next;
//display(start);//infinite loop means loop created.
loopDetect();
display(start);//No infinite loop means No loop now.

return 0;
}
/*
50 40 30 20 10
LoopDetected
50 40 30 20
*/
--------------------------
//Remove Loop in a linked list1.

C Linux code to insert in middle of Linked list

//Inserting After given node of Single Linked List
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
        int data;
        struct node* next;
};
struct node *start=NULL;
void push(struct node** ref,int d)
{
        struct node *newnode=(struct node *)malloc(sizeof(struct node));
        newnode->data=d;
        newnode->next=(*ref);
        (*ref)=newnode;
}
void display(struct node *start)
{
        struct node *ptr=start;
        while(ptr)
        {
                printf("%d\t",ptr->data);
                ptr=ptr->next;
        }
        printf("\n");
}
struct node* insertAfterNode(struct node *start,int d, int afternode)
{
int i;
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=d;
struct node* current=start;
while(current!=NULL)
{
if(current->data==afternode)
{
newnode->next=current->next;
current->next=newnode;
//return start;
}
current=current->next;
}
}
int main()

Singleton Design Pattern example in C++

//Singleton is a creational design pattern.
//A design pattern to provide one and only instance of an object.
//Declare the constructors of the class private.
//Declatre a static public instance of class type.
//Provide a static public method to get the instance
//If instance is NULL then only once create a object else
//return the already created instance
#include<stdio.h>
using namespace std;
class singleton
{
private:
singleton(){printf("Constructor called only once.\n");}
public:
static singleton* instance;
static singleton* getinstance();
};
singleton* singleton::instance=NULL;

singleton* singleton::getinstance()
{
if(instance==NULL)
{
instance = new singleton;//mind the syntax//no singleston s;
}
else
{
return instance;
}
}
int main()
{
//singleton s1;//singleton() is private within this context
singleton *sptr;
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
return 0;
}
/*
Constructor called only once.
*/

Observer Design Pattern example in C++


Observer Design Pattern example in C++

//Observer Design pattern Best Example.
//Observer Design pattern is implemented using two classes.
//First is observable or subject class: in this class even occurs and to be notified to the registered observers.
//subject class contains attachObserver(), notifyObserver(),and other task.
//Second class is observer class: class which wants to be notified when some even occurs in observable or subject class.
//observer class contains a pure viryual function notify().
//Example:
//When any event like new blog/article is available in a website it should notify to all the registered users.
//So here Blog will derived from subject class and
//users want to get notified of new articles. So User will be derived from class observer
#include<iostream>
using namespace std;
#include <vector>
#include <typeinfo>
#include <string>

class Subject;//forward declaration

class Observer//class which are interested to get notified
{
public:
    virtual void notify(Subject* s) = 0;//pure virtual function
    virtual ~Observer() {};
};

class Subject//Class in which even take place
{
    vector<Observer *> observers;
protected:
    void notify_observers()
    {
        vector<Observer *>::iterator iter;
        for (iter = observers.begin(); iter != observers.end(); ++iter)
            (*iter)->notify(this);
    }

public:
    virtual ~Subject() {};
    void register_observer(Observer* o)//pusshing the attached observers in a vector
    {
        observers.push_back(o);
    }
};

class Blog : public Subject
{
public:
    Blog()
    {
        cout << "New Article Posted." << "\n";
    }

    void eventTriggerNewArticle()
    {
        cout << "The new article event is triggered." << "\n";
        notify_observers();
    }

int const get_Blog_id()
//int get_Blog_id()
{
return 21022015;
}
};

class User : public Observer
{
public:
    virtual void notify(Subject* s)
    {
        Blog *a;
        a = dynamic_cast<Blog*>(s);
       cout << a->get_Blog_id() << "\n";
    }
};

int main ()
{
    Blog newArticle = Blog();
    User u = User();
    newArticle.register_observer(&u);
    newArticle.eventTriggerNewArticle();
    return 0;
}
/*OUTPUT:
New Article Posted.
The new article event is triggered.
21022015
*/

C++ program to overload operator+ for string concatenation

//operator overloading for concatenating two strings in C++
#include<iostream>
using namespace std;
#include<string.h>

class sample
{
private:
char str[20];
public:
sample()
{
cout<<"def constructor."<<endl;
strcpy(str,"C++ Linux Code.");
}
sample(char s[])
{
cout<<"a arg constructor."<<endl;
strcpy(str,s);
}
sample operator+(const sample& ref )
{
cout<<"overloaded + called"<<endl;
sample temp;//def constructor
strcpy(temp.str,str);
strcat(temp.str,ref.str);
return temp;
}
//return *this;//seg fault
void display(){cout<<str<<endl;}
};
int main()
{
sample s1;//def constructor
s1.display();
sample s2("blogspot.com");//1 arg constructor
s2.display();
sample s3;//def constructor
s3=s1+s2;
s3.display();
//cout<<str<<endl;//str was not declared in this scope. As str is private and only mf can access
//cout<<s1.str<<endl;//aaa
//cout<<'m'<<endl;//a
return 0;
}
/*
def constructor.
C++ Linux Code.
a arg constructor.
blogspot.com
def constructor.
overloaded + called
def constructor.
C++ Linux Code.blogs
*/

Copy constructor Overloaded assignment operator Destructor and default constructor implementation in C++

C++ program to implement:Default constructor, One argument constructor, Copy constructor, overloaded assignment operator, destructor and overload + operator to concatenate two strings in a single program.
#include<iostream>
using namespace std;
#include<string.h>

class sample
{
private:
char *name;
public:
sample(){cout<<"\n Default constructor called."<<endl;}
sample(const char *p);
sample(const sample &ref);
sample& operator=(const sample &obj);
sample& operator+(const sample& obj);
~sample();
};
sample::sample(const char* p)
{
cout<<" One argument constructor called."<<endl;
name = new char[strlen(p)+1];
strcpy(name,p);
cout<<"name: "<<name<<endl;
}
sample::sample(const sample &ref)
{
cout<<"copy constructor called."<<endl;
name=new char[strlen(ref.name)+1];
strcpy(name,ref.name);
}
sample& sample::operator=(const sample &ref)
{
cout<<"overloaded = operator called.\n";
//if(this==&ref)
//return *this;

//delete[] name;//Seg fault
name=new char[strlen(ref.name)+1];
strcpy(this->name,ref.name);
return *this;
}
sample& sample::operator+(const sample &obj)
{
cout<<"overloaded + called.\n";
//name=new char[strlen(obj.name)+1];
strcat(name,obj.name);
cout<<"cancatename is: "<<name<<endl;
}
sample::~sample()
{
cout<<"Destructor called.\n";
//delete[] name;
}
int main()
{
sample s1;//def constr.//destr
sample s2("Hello");//1 arg constr.//destr
sample s3(s2);//copy constr.//destr
sample s4=s3;//copy constr.//destr
sample s5;//def constr.//destr
s5=s1;//overloaded = opr.//No destructor
s2+s3;//overloaded + called//No destr
//cout<<s2.name<<endl;//name is private and accessible only by mf
return 0;
}
/*OUTPUT:
 Default constructor called.
 One argument constructor called.
name: Hello
copy constructor called.
copy constructor called.

 Default constructor called.
overloaded = operator called.
overloaded + called.
cancatename is: HelloHello
Destructor called.
Destructor called.
Destructor called.
Destructor called.
Destructor called.

*/

Writing and Reading File through C Linux Code

/* Writing to a file. Reading from a file */
#include<stdio.h>
int main()
{
    //writing to file
    FILE *fpw;
    fpw=fopen("1.txt","w+");
    fputs("Hello India\n",fpw);
    fclose(fpw);

    //Reading from file
    char buff[20];
    FILE *fpr;
    fpr=fopen("1.txt","r");
    fgets(buff,20,(FILE*)fpr);
    printf("%s\n",buff);
    fclose(fpr);
    return 0;
}
/*
 Hello India
 */

---------
/*
 Writing to a file
 Reading from a file
 Writing to another file
 */
#include<stdio.h>
int main()
{
    //writing to file
    FILE *fpw;
    fpw=fopen("1.txt","w+");
    fputs("Hello India\n",fpw);
    fclose(fpw);

    //Reading from file
    char buff[20];
    FILE *fpr;
    fpr=fopen("1.txt","r");
    fgets(buff,20,(FILE*)fpr);
    printf("%s\n",buff);

        //Writing to another file
    FILE *fpo;
    fpo=fopen("22.txt","w+");
    fputs(buff,fpo);
        //fprintf(fpo,"%s",buff);
    fclose(fpr);
    fclose(fpr);
    return 0;
}
/*
 Hello India
 */

---------

/*
 Writing and reading to and from file
 */
#include <stdio.h>
int main()
{
    /*Writing to a file*/
    FILE *fp;
    fp = fopen("test.txt", "w+");
    fprintf(fp, "This is testing for fprintf...\n");
    fputs("This is testing for fputs...\n", fp);
    fclose(fp);

    /*Reading from a file*/
    FILE *fp1;
    char buff[255];
    fp1 = fopen("test.txt", "r");
    fscanf(fp1, "%s", buff);//upto space
    printf("1 : %s\n", buff );

    fgets(buff, 255, (FILE*)fp1);//upto new line
    printf("2: %s\n", buff );

    fgets(buff, 255, (FILE*)fp1);//last line
    printf("3: %s\n", buff );
    fclose(fp1);

    return 0;
    }
/*
1 : This
2:  is testing for fprintf...
3: This is testing for fputs...
 */
/*
 The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. 
It copies the read string into the buffer buf, appending a null character to terminate the string.
We can also use int fscanf(FILE *fp, const char *format, ...) function to read strings froma file but it stops reading after the first space character encounters.

IPC and Sockets Programs in C in Linux Platform

IPC: Inter Process Communication means exchanging messages or data between processes.
Processes can reside on same machine or in separate machines in a network according to which IPC or Socket is used.

Traditional IPC:
1. Pipes:Only related Processes can communicate as only child can share the file descriptor of parent.
2. Fifo(named pipes): since fifo has name so it can be opened by other processes for read write.

System V IPC:
1.Message Queue
2.Semaphore
3.Shared Memory

Socket Programming/ Network programming:
Traditional and System V IPC can be used by processes whicce run on the same machine not over the Network.For the Processes that run on different machines "socket" is used. Socket can be thought of extended System V IPC. Socket Can be thought of end point of a communication channel.
Networking Programming generally follow Client Server model. Server runs forever and waits for requests from clients.Client requests for services from server. Server process the request and send to client.Browsers can be thought of http clients that requests for html pages from http/web servers.

In C programming generally Berkeleys Socket APIs are used for socket programming. Other APIS like TLI(Transport Layer Interface of system V) are also available.

Socket System Calls:

Used by Serverer           Used by client
socket()                  Socket()
bind()
listen()
accept()<----------------------connect()
read/recv/recfrom<---------write/send/sendto
write/send/sendto---------->read/recv/recfrom
close()           close()

Server Program:
First step of any network program is to create a socket using socket() system call.And, initialize the server_address with family,IP and Port.
Then created server is bind() with the server_Address and port on which then server listen() for incoming connections from client. Then server
accept() a connection from client and then read()/write() and finally close() the socket.
Client Program:
Client Program also start with creating a socket() and initialization of server socket with family,IP and port.Then connect() with the server and write()/read() and finally close() the socket.

Note:Apart from read() and write() in socket programming send()/recv() with tcp and sendto()/recvfrom() with udp can also be used.

Note :System V IPC ie message queue, semaphore and shared memory can not use read write as they are not implemented by the kernel.
Message Queue uses below API:
msgget()
msgctl()
msgsnd()
msgrcv()
Shared Memory Uses below api:
shmget()
shmctl()
shmat()
shmdt()
Semaphore uses below api:
semget()
semctl()
semop()

System V semaphore are complex so generally they are wrapped around pthread like semaphore functions.

You may like:

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network

C Linux Code for multi threaded socket client/Server file sharing ftp

POSIX Semaphore Implementation Example code in C on Linux

POSIX Mutex Implementation C Program in Linux


Threaded Concurrent echo TCP Server Code in C in Linux Platform

//TCP SERVER Concurrent:muliple clients can be handled by this server
//Now second client no need to wait for first client to close by finishing its task.
//This server now handles 5 clients simueltaneously. i.e. Now Upto 5 clients simueltaneously can send and receive messages from this server.
//Here concurrency is achieved  by creating a new thread which process  each new client while parent continues to accepting new connections.


#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define MAXSZ 100
void* funcTask(void *arg);

int main()
{
int sockfd;//to create socket
int newsockfd;//to accept connection

struct sockaddr_in serverAddress;//server receive on this address
struct sockaddr_in clientAddress;//server sends to client on this address

int n;
char msg[MAXSZ];
int clientAddressLength;
int pid;
pthread_t serverThread;

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=htonl(INADDR_ANY);
serverAddress.sin_port=htons(PORT);

//bind the socket with the server address and port
bind(sockfd,(struct sockaddr *)&serverAddress, sizeof(serverAddress));

//listen for connection from client
listen(sockfd,5);

while(1)
{
//parent process waiting to accept a new connection
printf("\n*****server waiting for new client connection:*****\n");
clientAddressLength=sizeof(clientAddress);
newsockfd=accept(sockfd,(struct sockaddr*)&clientAddress,&clientAddressLength);
printf("connected to client: %s\n",inet_ntoa(clientAddress.sin_addr));

pthread_create(&serverThread,NULL,&funcTask,(void *)newsockfd);
}

return 0;
}
void* funcTask(void *arg)
{
int n;
int newsockfd=(int)arg;
char msg[MAXSZ];

pthread_detach(pthread_self());
while(1)
{
n=recv(newsockfd,msg,MAXSZ,0);
if(n==0)
{
close(newsockfd);
break;
}
msg[n]=0;
send(newsockfd,msg,n,0);

printf("Receive and set:%s\n",msg);
}
close(newsockfd);
}
/*
ms@ubuntu:~/ipc_socket$ gcc server.c -o s -lpthread
ms@ubuntu:~/ipc_socket$ ./s

 *****server waiting for new client connection:*****
 connected to client: 127.0.0.1

 *****server waiting for new client connection:*****
 Receive and set:India

 Receive and set:is

 Receive and set:Great

 connected to client: 127.0.0.1

 *****server waiting for new client connection:*****
 Receive and set:The

 Receive and set:USA

 */
/***************CLIENT ITERATIVE*******************/

#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define SERVER_IP "127.0.0.1"
#define MAXSZ 100
int main()
{
int sockfd;//to create socket

struct sockaddr_in serverAddress;//client will connect on this

int n;
char msg1[MAXSZ];
char msg2[MAXSZ];

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=inet_addr(SERVER_IP);
serverAddress.sin_port=htons(PORT);

//client  connect to server on port
connect(sockfd,(struct sockaddr *)&serverAddress,sizeof(serverAddress));
//send to sever and receive from server
while(1)
{
printf("\nEnter message to send to server:\n");
fgets(msg1,MAXSZ,stdin);
if(msg1[0]=='#')
break;

n=strlen(msg1)+1;
send(sockfd,msg1,n,0);

n=recv(sockfd,msg2,MAXSZ,0);

printf("Receive message from  server::%s\n",msg2);
}

return 0;
}
/*
client:
ms@ubuntu:~/ipc_socket$ gcc tcpclient.c -o c
ms@ubuntu:~/ipc_socket$ ./c

Enter message to send to server:
India
Receive message from  server::India

Enter message to send to server:
IS
Receive message from  server::IS

Enter message to send to server:
Great
Receive message from  server::Great

Enter message to send to server:
*/

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network


C Linux Code for multi threaded socket client/Server file sharing ftp


Concurrent Server handling Multiple Clients Code in C in Linux Platform

//TCP SERVER Concurrent: multiple clients can be handled by this server
//Now second client no need to wait for first client to close by finishing its task.
//This server now handles 5 clients simultaneously. i.e. Now up to 5 clients simultaneously can send and receive messages from this server.
//Here concurrency is achieved  by creating a new child process which process e each new client while parent continues to accepting new connections.
#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define MAXSZ 100
int main()
{
int sockfd;//to create socket
int newsockfd;//to accept connection

struct sockaddr_in serverAddress;//server receive on this address
struct sockaddr_in clientAddress;//server sends to client on this address

int n;
char msg[MAXSZ];
int clientAddressLength;
int pid;

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=htonl(INADDR_ANY);
serverAddress.sin_port=htons(PORT);

//bind the socket with the server address and port
bind(sockfd,(struct sockaddr *)&serverAddress, sizeof(serverAddress));

//listen for connection from client
listen(sockfd,5);

while(1)
{
//parent process waiting to accept a new connection
printf("\n*****server waiting for new client connection:*****\n");
clientAddressLength=sizeof(clientAddress);
newsockfd=accept(sockfd,(struct sockaddr*)&clientAddress,&clientAddressLength);
printf("connected to client: %s\n",inet_ntoa(clientAddress.sin_addr));

//child process is created for serving each new clients
pid=fork();
if(pid==0)//child process rec and send
{
//rceive from client
while(1)
{
n=recv(newsockfd,msg,MAXSZ,0);
if(n==0)
{
close(newsockfd);
break;
}
msg[n]=0;
send(newsockfd,msg,n,0);

printf("Receive and set:%s\n",msg);
}//close interior while
exit(0);
}
else
{
close(newsockfd);//sock is closed BY PARENT
}
}//close exterior while

return 0;
}
/*
*****server waiting for new client connection:*****
connected to client: 127.0.0.1

*****server waiting for new client connection:*****
Receive and set:India

Receive and set:is

Receive and set:Great

connected to client: 127.0.0.1

*****server waiting for new client connection:*****
Receive and set:The

Receive and set:USA
 */

/************Client Code***********/
//CLIENT ITERATIVE

#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define SERVER_IP "127.0.0.1"
#define MAXSZ 100
int main()
{
int sockfd;//to create socket

struct sockaddr_in serverAddress;//client will connect on this

int n;
char msg1[MAXSZ];
char msg2[MAXSZ];

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=inet_addr(SERVER_IP);
serverAddress.sin_port=htons(PORT);

//client  connect to server on port
connect(sockfd,(struct sockaddr *)&serverAddress,sizeof(serverAddress));
//send to sever and receive from server
while(1)
{
printf("\nEnter message to send to server:\n");
fgets(msg1,MAXSZ,stdin);
if(msg1[0]=='#')
break;

n=strlen(msg1)+1;
send(sockfd,msg1,n,0);

n=recv(sockfd,msg2,MAXSZ,0);

printf("Receive message from  server::%s\n",msg2);
}

return 0;
}
/*
client:

ms@ubuntu:~/ipc_socket$ gcc tcpclient.c -o c
ms@ubuntu:~/ipc_socket$ ./c

Enter message to send to server:
India
Receive message from  server::India


Enter message to send to server:
IS
Receive message from  server::IS


Enter message to send to server:
Great
Receive message from  server::Great


Enter message to send to server:
*/

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network


C Linux Code for multi threaded socket client/Server file sharing ftp