Wednesday, 31 December 2014

Process and Process management in UNIX

Process and Process management: 




Some library functions works for OS and some other works for specific purpose.

 API---Application Programming Interface(taking help of library)
 SCI--- System call interface
 .dll file of one OS can’t be accessible by another OS.

 fread--- is a function used to read binary data and store in memory based on requirement.

 Syntax:
int fread(int,void *,int);


Manual page:    


#man fread  

fgets---only read characters.



To view system call: 
 #man then press enter 

 Ex:
 #man cal    ----- to view calendar.





In order to communicate with OS we need system calls. fread &read are used for same purpose.
But fread has some limitations compared to read. To view the limitations of read over fread see the following manual pages

#man read
#man fread

What are the differences between programs,application and process? 
 Source code is called as program.
Multiple source codes or object files combination will give us single application.
These all source codes doesn’t occupy different memory locations.
 The combination of all source codes will give us one executable. For that executable file only memory will be created. That executable is called as process.
Running instance of an application is called as process.

What is CPU scheduling or process scheduling?


#include<stdio.h>
main()
{
printf(“executing…”);
while(1)
}

If we run this program in two terminals, both are in running mode.
 P1,P2 be the two processes corresponding to terminal 1, terminal 2.
 P1,P2 demands the CPU simultaneously. One CPU is only the resource for multiple processes.
 Here CPU manages both the processes. This is called “CPU scheduling or process scheduling”.
Here process 1, process2 executables located at different memory locations.

 Define process management?
 Managing CPU for multiple processes efficiently is called process management. 

Define multi-tasking? 
Demanding CPU for multiple processes simultaneously is called multi-tasking.

What is life of process? 
Program execution comes into life when the program loaded from secondary memory to primary memory. And after execution of program, the memory will be released from primary memory.

#ps    ----to view currently running processes


Every process having it’s own(unique) process id’s.
Process id of a particular process changes for every execution. Which is not fixed.

Bash---- one of the process running for longer time.(bourne Against Shell)

#bash ..... to display command prompt
#cal

Here bash takes calendar as input. This command is accepted. It is being executed. 
Then the process is terminated and looks for another input command.

Bash: 
process life is so long. Hence, each and every time cursor waits for input.
For some of the processes, the life time is more. For some of the processes life time is less.
Based on the nature of the job, process life will be decided.

#date --- to display date
Here life of process is shorter.

 Example:Long job

main()
{
printf(“executing…”);
while(1)
}
In this example, life of process is infinite.

 How to display process ID?

main()
{
printf(“process:%d\n”,getpid());
}

We can save this program as p1.c

getpid()----to display process ID

#./p1    (to view output ID)

How to put process in waiting mode?


main()
{
char ch;
Printf(“process:%d\n”,getpid());
ch=getchar();
}
Read More

Tuesday, 30 December 2014

Copy Constructor in C++ to reduce code complexity

Copy constructor: 

 Extract the source into destination element by element.
 Here the size of class name has been passed.
 Here both objects have different sizes.
 Here one element will be taken as source and put it onto destination.
 Like this entire object data is copied into destination. Hence it called “copy constructor’.

class Vector
{
int size;
int *v;
Vector(int s)
{
size=s;
v=new int[s];
}
void get()
{
for(int i=0;i>v[i];
}
};
Vector(Vector pv)
{
size=pv.size;		//sizeof(v1)
v=new int[size];
for(int i=0;i 
Here v1-> actual parameter Pv-> formal parameter Here compiler will not copy the entire data from one object to other object directly. 
It has to be done by user element by element. V1 values is to be copied into v2 by using constructor. 
The compiler will not take care while copying  ‘v1’data into ‘v2’. 
Hence user defined constructor is used while copying the data of ‘v1’ into  ‘v2’.
We will take the help of ‘copy constructor’ when the object is copied into another object.

A constructor can take anything as an argument. except same class object.

Note: same class object reference can be the parameter for a constructor . a constructor which is having same class object reference as a parameter, it is called “copy constructor”.
Constructor gets invoked when object creation occurs.
Vector v2;
Vector v1;	default constructor

Vector v2=v1;
Vector v2(v1);		Copy Constructor.

Example Program to explain the concept of constructors:
#include<stdio.h>
using namespace std;
class test
{
public: test()
{
cout<<”default constructor invoked”<
Output: default constructor invoked. Program to print sum of vector by using copy constructor
#include<stdio.h>
class Vector
{
private:
int size;
int *v;
public:
Vector(int s)
{
size=s;
v=new int[s];
}
Vector(vector &vr)
{
size=vr.size;
v=new int[size];
for(int i=0;i>v[i];
}
}

void show()
{
cout<<”elements of vector are”<
Destructors: Complements the job of constructor is called as “destructor”. 

Let us consider a simple example for gmail. When we try to open gmail account, when user name and password are matched with database. Then only object created. Constructors executes when object is created. Destructor executes when object goes to die.

Syntax:
~Bag()
{
………..
……….
}
Before object goes to die, if any operations we want to perform are going to be written within this block only. Object creation process construct the constructor. Object destroy process destroy the destructor.

If the scope of the variable exist within the block, then only the object is said to be alive.

main()
{
test1()
{
test2()
{
………
………..
}		//test2 alive up to here only
……..
……….
}
Once the object is created, it needs to destroy after using. The complement function need to be made as public to destroy the object of main function. We don’t need additional parameters to destroy the object.

Example to manually destroy the created constructor.

Vector(int s)
{
size=s;
V=new int[s];
}
~vector()
{
delete []v;
}
Destructor is a special member, which gets invoked at the time of destroying an object. Destructor will have the same name as class name preceding with tilt(~) operator.

Syntax: 
	
~class-name()
{
………
…………
}
Destructors will not have any parameters. Destructors must be in the public section itself. Destructor means, complement the job of constructor. Example:
void fun()
{
Test fo;
}
Class Test
{
Public:
Test()
{
Cout<<”constructor”<

Read More

Dynamic memory allocation in C++

Dynamic memory allocation in C++: 

 “New” is an operator in c++. Which is used to allocate the memory dynamically.

In C, dynamically memory allocation:
Int *p;
P=malloc(n*sizeof(int));

Here malloc is a library function.
If malloc is success, void pointer is returned.
If malloc fails then NULL pointer is returned.
If (n*sizeof(int)) is success, then only type casting allowed.

 In C++, dynamic memory allocation:
Int *p=new int[5];
Data_type *pv;
pv=new Data_type[size];

Here we are using integer array. Hence return type is integer pointer.
What are the advantages of ‘new’ operator in C++ for dynamic memory allocation? 
Exception Handling: while running programs, some exceptions(errors) occurs during memory allocation. In C, we can’t able to identify the particular error with proper error message.
     
But in C++, ‘new’ is an operator. It will give proper message to programmer. Then user can take required action over there.
        If allocation is success, then integer pointer is returned. If an error occurs then, ‘new, will through an exception rather than NULL pointer.

 Malloc returns NULL pointer on failure. Which doesn’t give proper exception handling message. This is one of the advantage of ‘new’ compared to malloc().

              ‘New’ is an operator, which can be over loadable. ‘new’ has enhanced version, that means we can have privileges to design new memory allocation based on user requirement. User can be able to define memory allocation function(user defined memory allocation function) with the help of ‘new’.

              But, by using malloc predefined library functions, only we can able to create memory. User defined privileges are not given for creation of malloc().

              In C, free() is a keyword to free or de-allocate memory after usage. The freed memory will be utilized by remaining part of program while at runtime. In C++, delete() is a keyword which de-allocates the memory which has been allocated by ‘new’ operator only.

Syntax:
To delete(free) the memory in C++,
int *p=new int[5];		//to create memory for 5 integers
float *fp=new float[5];
double *dp=new double[5];

Data_type *pv=new data_type[size];   Here the data type may be a class or object.

Example:

Height **p=new Height();
int *p=new int(10);	    // to store integer 10 into address of pointer p
Height *my_height=new Height[3];  //  here 3 objects created
Height *myh= new Height(10);	//Here only, one object is initialized.
int *p=new int[5];
delete p;	//to delete or free variable memory
delete []p;	//to delete array


What is dangling pointer problem in C++

int *p=new int(10);
………….
………….
delete p; 	//here we are deleting memory location
……………..
……………..
p=new int(50);	//here we are trying to access deleted memory.  This is called    
                //dangling pointer problem
 
int *p=new int(10);
…………..
………….
p=new int(50);	//memory leak occurs here. Because we are trying to replace      //existing variable with new one.
…….
……………….
Example:
class Bag
{
int item_count;
int contents[5];
}
This is for fixed number of objects
Read More
Functions of network devices

Separating (connecting) networks or expanding an existing network. 
Examples: repeaters, hubs, bridges, routers, switches, gateways  are used to provide communication between network devices.

Network devices used for Remote access

Example: Remote access devices are 56K Modems and ADSL modems

we should follow the following steps while Expanding Network

Networks cannot be made larger by simply adding new computers and more cables. it is Less efficient.
large LAN to be divided into various segments to form smaller LAN's
These LAN's should be connected using the following components.
LAN segments connected using Repeaters, bridges, routers, switches or gateways.

Why we need to use Repeaters and Hubs in Network Communication?

Repeaters or hubs works at the OSI physical layer to regenerate the network’s signal and resend them to other segments. Hubs will regenerates data and broadcasts them to all ports

what are the Limitations and Features of Hubs?


Cannot link unlike segments
Cannot join segments with different access methods (e.g. CSMA/CD and token passing)
Do not isolate and filter packets
Can connect different types of media
The most economic way of expanding networks
Bridges:
Bridges Has one input and one output
Bridges Used to isolate network traffic and computers
Bridges Has the intelligent to examine incoming packet source and destination addresses
Bridges cannot interpret higher-level information


How Bridges Work?
Bridges work at the Media Access Control Sub-layer of the OSI model
Routing table implemented to record the segment address
If destination address is in the same segment as the source address, stop transmit. Otherwise, forward to the other segment.











Read More

Monday, 29 December 2014

Overview of UNIX system

who invented UNIX system?

UNIX system was first described in 1974 by ken Thompson and Dennis Ritchie.
Thompson and Ritchie implemented the UNIX On PDP-7 computer and later on PDP-11
( 1971 )
In 1973 the UNIX was written in C programming language.

Architecture of UNIX System

What are inputs and outputs of UNIX system?
Each and Every file has its own file descriptor. file descriptor contains the information related to weather we are reading data from file or writing data to the file.

              1.Input and output uses file descriptors.
              2.Small non-negative integers .
              3.All shells open three descriptors
        a.standard input(stdin: default return value is 0) 
     b.standard output(stdout: default return value is 1) 
      c.standard error(stderr: error number will be returned)

What is meant by Program?

Collection of instructions and data in a file is called program. 
File contents are arranged according To the rules established by kernel. 
After compiling program, we will get an object file. This object file resides on the hard disk. 
List of instructions read from memory and executed by kernel. 

Explain the need of process in UNIX Operating System?
An executing instance of a program is called process. 
Kernel creates a new process.
environment in which program executes is also called as process.
Creation of new process is done By issuing a system call.
The program is used to initialize Instructions and User data.

Process system data includes the following attributes
 Current directory.
Open files.
Descriptors.
Accumulated CPU time…
A process cannot access/ modify The system data directly.

Process ID and Process Groups
Every process has a process ID.
Guaranteed to have unique positive integer.
All processes have a parent
Related processes can be organized into process groups.
One group member is the group leader.
Each member has the process-group-ID.
A process group can have a control terminal
When group leader terminates, All process with the same control terminal are sent hangup signal.
Process ID        Uniquely identifies a process.
Parent-process ID      Process -ID of the process’s parent
Process group ID        Process ID of the group leader
Permissions in UNIX.
positive integers associated with user’s login name Called Real user ID,Real group ID.
Two ID’s associated with a process are effective user ID and effective group ID.
Error Handling in UNIX.
Most Unix system calls return Negative value on error.
The global variable errno Is set to a value for more information.
The file  < errno.h >  defines the variable errno.
The value of errno is not cleared,if an error does not occur.
The value of error is never set to 0 (zero).
Two functions to print error message
strerror( )
perror( ).
System Calls in UNIX Called service points for kernel service.
The system calls are one feature of UNIX That cannot change.
Unix version 7 has  50 system calls.
4.4 BSD  has 110system calls.
SVR4 has  120 system calls.

Header files of UNIX:
1)dirent.h   is for Directory entries
2)errno.h  is for Error codes
3)fcntl.h  is for File control
4)signal.h  is for Signals
5) stddef.h  is for  Standard definitions
6) stdio.h    is for Standard I/O 
7) string.h    is for string operations
8) time.h   is for time and date

Headers for IPC
9) sys/ipc.h  is for  IPC
10) sys/msg.h  is for  Message Queues
11) sys/sem.h  is for  Semaphores
12) sys/shm.h   is for Shared memory
13)sys/stat.h   is for file status
14)sys/times.h   is for Process times
15)sys/types.h  is for   Primitive system data types
16)sys/wait h   is for Process Control

What are the features of UNIX OS(operating system)?

1.Simple user interface.
2.Hierarchical file system.
3.Simple, Consistent interface to devices.
4.Protection of file data.
5.Peripheral devices treated as files.








Read More

Wednesday, 17 December 2014

Important feature of C++: Encapsulation


Encapsulation: Binding the details(int,char,float,string) together in a class is called encapsulation.


  Class is also like a structure. Compared to structures, C++ class has the following extra features

Features of class in C++:

1) Protect

2) Private

3)Public



Above declared variables can be visible to everywhere in our program. 

Because, we have mentioned that the class variables are public.

Creating a class variable is called “object”.

Enhancing this object from class is called “enhancement”.


Here the scope of variables is within the class itself. Class data members will not be accessed by others except limited persons(authorized). Members/functions can only accessed by private persons only.


Here it will give syntax error. If we place public instead of private, it will execute successfully.



To access data  outside function, we need to use the following format in main function.



To access data inside function, we need to use the following format.



Write a program to set and display data



Write a program to set date


Program to find sum of two numbers



We can declare a function within a class or outside a class.
Example program to write function outside class.



Here both get() functions are not same. One is related to class. Another one is general function.
All functions which are defined in class are to be considered as inline.


Syntax:



We need to add inline if the function definition is outside the class.



Example: program to find height of two persons( passing objects as arguments)


Read More

Tuesday, 16 December 2014

inline to reduce transitions between function calls

inline is a keyword to execute a particular function repeatedly in inline fashion.

This concept comes into role to reduce the code size.

Actually code size not reduced. Number of lines of program can be reduced.

Requesting the compiler to replace the function body in the calling function place is called inline.

Benefits of inline keyword: 

1) Number of transitions between calling function and called function can be reduced.

2) Same stack memory can be used.
Rules to follow while using inline keyword:

1) Inline functions has to be defined before it is calling.

2) Inline is a request. It’s not an order.

3) There is no 100% guarantee that, inline requested functions will execute in inline fashion itself only.

4) Inline function should not contain any looping statements.

Here the compiler takes many number of transitions. Due to this, lot of time of CPU will get wasted. To avoid this, we have to use inline keyword.
Here number of transitions reduced and the same stack memory used.

Macro’s only replaces the code. Macro’s doesn’t know the passing parameters type.

C++ compiler enhanced the functions compared to C compiler.

Some times we can’t able to get exact results in C for macro related operations. But this problem can be


achieved by using inline keyword in C++. By using inline we can achieve exact results.


Read More

Function overloading Concept with lot of examples

The following rules are applicable for implementing function overloading concept.

1)      Function name should not be a keyword. Meaningful name should be given to function names and variables.
1)      C++ allows more than one function with the same name with signature. This concept is called “function overloading”.
Signature means either the number of parameters or data types of parameters or order of parameters should be different. Return type should not be considered as a signature.

C++ compiler is strict checking type. If we pass integer variables as arguments then calling function goes to 1st block in above program.
This concept is called function overloading. In-spite of we are passing so many arguments instead of required arguments, only 1st few arguments will be taken into consideration. 
 Here 3rd parameter is rate of interest. It always takes 5 as rate of interest. It won’t show errors inspite of we are passing two arguments.
Compile time error.

        While implementing default arguments, we should not overload the function with leftover arguments.

Here the default argument is r=5. If we pass two arguments then the compiler gets confused to select particular function.

Here this is valid. Instead of using function overloading concept, by making additional arguments as zero, we can get better results for same function.
Read More