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

Monday, March 21, 2016

Difference between shared memory and message queue

Both shared memory and message queues can be used to exchange information between processes.The difference is in how they are used.

Shared memory is exactly what you'd think: it's an area of storage that can be read and written by more than one process.
 It provides no inherent synchronization; in other words, it's up to the programmer to
 ensure that one process doesn't clobber another's data.
  But it's efficient in terms of throughput: reading and writing are relatively fast operations.

A message queue is a one-way pipe: one process writes to the queue,
and another reads the data in the order it was written until an end-of-data condition occurs.
When the queue is created, the message size (bytes per message, usually fairly small)
and queue length (maximum number of pending messages) are set.
Access is slower than shared memory because each read/write operation is typically a single message.
But the queue guarantees that each operation will either processes an entire message successfully or fail
 without altering the queue. So the writer can never fail after writing only a partial message, and
 the reader will either retrieve a complete message or nothing at all.

Simple wrapper examples for networking code

Following are few wrappers used for networking code.. Mainly for sockets

int nRead(int fd, char* ptr, int nBytes)
{
    int nleft = nbytes ;
    int nread ;
   
    while (nleft>0)
    {
        nread = read(fd, ptr, nleft) ;
        if (nread == 0)
            break ;
           
        if (nread<0)
            return nread ;
           
        nleft = nleft - nread ;
       
        ptr = ptr+nread ;
    }
   
    return nbytes - nleft ;
}
   

int nWrite(int fd, const char* ptr, int nBytes)
{
    int nleft = nBytes ;
    int nwrite ;
   
    while (nleft >= 0)
    {
        nwrite = write(fd, ptr, nleft) ;
        if (nwrite <=0)
        nleft = nleft - nwrite ;
        ptr = ptr + nwrite ;
    }
    return nBytes - nleft ;
}
           
int setNonBlocking(int fd)
{
    int flags ;
    if (flags = fcntl(fd, F_GETFL) < 0)
    {
        perror("GETFL") ;
        return -1 ;
    }
   
    if (fcntl(fd, F_SETFL | flags) < 0)
    {
        perror("SETFL") ;
        return -1 ;
    }

    return 0 ;
}

Static functions

Why people love to ask about static functions is no idea. But the fact is that static functions are just an extra-ordinary functions compared to normal functions.

Gotchas while using Static functions.
1) Static functions are limited to file where they are declared.
2) You can define the same name of the function in another file.
3) Global functions have global scope, meaning function defined in one file can be accessed by other module.

Example for static function
File1.c
static void fun1()
{
    printf("I am a static function") ;
    return ;
}

The keyword static  makes the function as static and the call will be used only within File1.c file.

Another example
File2.c
static void Func2()
{
      printf("Another static demo\n") ;
      return ;
}

File3.c
void Func2()
{
     printf("This is normal function") ;
     return ;
}

main.c
int main()
{
    Func2() ;
    Func2() ;
}

The fuction Func2() is defined twice. If static function was used you will get an error. Both File2.o and File3.o can used to create an executale main.o(main.c).

Friday, March 18, 2016

Arrays

Arrays are nothing but elements of same type stored in contigues manner.
A list of programmers working in a company, list of softwares installed in computer. For example there 10 programmers and 200 softwares installed in the computer.

10 programmers, 200 softwares but they are not same type, how come arrays will be used. Yes, 10 programmers are just numbers we are not interested on each person whether he is male or female, young or old, black or white etc.
Confused leave that example.

IF there are 100 apples, then we can store these apples in array. Thats it.
We have one dimensional, 2 dimensional and upto n-dimensional array.
All n-dimensional arrays are again each 1-dimensional array.

Properties of arrays
1) Arrays should be same data type and cannot be mixed with other data types.
examples
int apple[100], float money[100], char names[500] etc.
Each one is unique.

2) Arrays will always start with index 0 and ends with <n> -1.
In the above example, loop your variable from 0 to 99, 0 to 499 etc to access each item from the array.

3) Arrays can be statically created or dynamically created. Above example shows static allocation.
Dynamically create the array as follows
int *p = (int*) malloc(100*(sizeof(int)) ;
and access using p[0], p[1] etc. and remember to free after the usage.


Memory layout of C program

A typical C program contains the following segments
1) text segment
2) data segment - initialized
3) data segment - unintialized
4) stack
5) Heap


Text segment is the actual c program. The whole C program will be stored in this segment. Actual code is the executable instructions CPU use for execution.
This segment is normally sharable, I mean this section can be shared to editors like vi, vim, ed, shells, and the compilers. Normally this segment will be below the stack or heap.

Data segment: Data segment can be read only or read write. All the global and static variables stored in this segment.
This segment can be divided into initialized data segment where the variables with some values will be stored and uninitialized data segment where variables without initialization will be stored.
Examples:
int a = 100;
char s = 'T' ;
The variables a and s are stored in intialized data segment

char m ;
int i ;
m and i will be stored in uninitialized data segments. This segment is also called BSS(Block started by Symbol)

what about static variables. The memory for static is also stored in data segments.
Example:
static int a = 100;
static float m = 10.34 ;
Note:If static variables will not initiliazed, then they will be set to zero.
So there is no concept of initialized and unitialized data segments for static variables.

Now one more missing section in data segment is READ ONLY.
The global/static variables with read only will be stored in "READ ONLY segment"

Typically data segment can be read only and read-write. All const data variables will be used in READ only data segment and rest in read-write data segments.

Example:
char test[] = "Lets Make Simple" ;
The string literal "Lets Make Simple" is stored in read-only segment while variable test is stored in read-write segment.


STACK segment: As expected used to store the local variables of the function. It contains program stack in LIFO(Last in First Out) fashion. The top of the stack is always the first to be removed from the stack. The register called stack pointer maintain the top of the stack and this will be adjusted as and when function is called and returned. The stack grown opposite to heap area.
Recursion programs use the best use of stack. The stack pointer keeps a seperate copy of each address of called and calling function and hence allocates fresh copy of address for each function call.
int main()
{
   main() ;
}

main() called recursively, as expected we got stack overflow error. Since there is no exit from stack(no exit in the functions).
Typically stack grown from higher address to lower address. Memory for these variables will be de-allocated when the function exits.

HEAP segment: Memory in this segment will be altered when you call malloc, new, free, delete, realloc. They are used to allocate memory dynamically. Heap and stack grows opposite to each other.  Memory in this segment are not freed automatically like stack. You need to call free(), delete() to free the memory from this region.

To know the memory allocated for your program use size command. It shows the size of each segment.