Posts

Showing posts from May, 2015

C program to reverse the contents of an array without using temp variable

#include <stdio.h> void printArray(int *arr, int length) { int i; for (i = 0; i < length; i++) printf("%d\t", arr[i]); printf("\n"); } void reverseArray(int *arr, int length) { int i; for (i= 0; i < length/2 ; i++) { arr[i] =arr[i] + arr[length - i -1]; arr[length - i - 1] = arr[i] - arr[length - i - 1]; arr[i] = arr[i]- arr[length - i - 1]; } } int main() { int arr1[5] = {1, 2, 3, 4, 5}; int i; printf("Array Contents Before Swapping\n"); printArray(arr1, 5); reverseArray(arr1, 5); printf("Array Contents After Swapping\n"); printArray(arr1, 5); return 0; }

MultiThreading in C Tutorial - Part 8(Semaphore)

API for semaphores: Header file: #include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned int value); It is used to initialized the semaphore,with the initial value of the semaphore set to the value passed in the third argument.. pshared is used to indicate whether you want to share the semaphore between process or threads. if pshared value is zero it is shared between threads else it will be shared between processes. If you are trying to initialize already initialized semaphore,the result is undefined behaviour. int sem_destroy(sem_t *sem); Initialized semaphores that are not currently blocked can be destroyed by using sem_destroy api. int sem_wait(sem_t *sem); It decrements the value pointed by the semaphore.If the value is greater than zero then the function returns immediately,if the value is zero then it is blocked until the value is greater than zero so that it can decrement it. int sem_post(sem_t *sem); sem_post increments(unlocks) the

MultiThreading in C Tutorial - Part 7 Mutex

Mutexes are used to provide  exclusive access to a shared resource .Mutex stands for Mutual Exclusion. POSIX API's for Mutex: int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr); This function initializes the mutex with the attributes passed in the second argument.If the second argument is NULL then default attributes are applied.Upon successful initialization, the state of the mutex will be initialized and unlocked. int pthread_mutex_destroy(pthread_mutex_t *destroy); It is used to destroy the mutex specified in the argument and its state become uninitialized.Once destroyed you can still use it to reinitialize.Note that if you are trying to destroy the mutex when it is locked it will result in undefined behaviour. If you want a  mutex with default attributes, the macro PTHREAD_MUTEX_INITIALIZER can be used. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; The above statement is similar to calling pthread_mutex_init with second argum

MultiThreading in C Tutorial - Part 6(Attributes)

We know that the second argument we pass to the pthread_create is attributes,when we pass it NULL it will take the default attributes.We will see what are the default state of the attributes. Example code to print the default attributes: #include <stdio.h> #include <pthread.h> #include <stdlib.h> void attr_dump(pthread_t thread_id) { pthread_attr_t attr; void *stkaddr; size_t stksize, guardsize; int thread_state, schedpolicy; /* * pthread_getattr_np : gets the attributes of the thread specified * in the first argument */ pthread_getattr_np(thread_id, &attr); printf("Printing Default Attributes\n"); /* * Read stack size and stack address */ pthread_attr_getstack(&attr, &stkaddr, &stksize); printf("Stack Size:%d bytes\n",stksize); printf("Stack Address:%p\n",stkaddr); /* * Read whether it is detached state or joinable state   */ pthread_attr_getdetachstate(&

C Function to check occurrence of a character in a particular string

/*  * Returns index of the first occurrence of the character  * else returns -1 if the character is not present  */ int checkChar(char *string, char ch) {         int index;          if(string == NULL)                     return -1;          for (index = 0 ; index < strlen(string); index++)          {                 if(string[index] == ch)                        break;            }            if(index == strlen(string)                       return -1;           return index; }

C program to find out the endianess of the machine/processor

Endianess specifies the way how multiple bytes are stored in the memory. There are two types:Little Endian and Big Endian. Little Endian: In little endian, Least significant byte is stored first of the multiple data bytes; For example, if you are trying to store 0x12345678,then 0x78 is stored first. Big Endian: In big endian, Most significant byte is stored first of the multiple data bytes. For example, if you are trying to store 0x12345678, then 0x12 is stored first. We will see different ways of finding endianess of your machine: Method 1: int main() {       unsigned int i = 1;       char *ch = (char  *)&i;       if (*ch)             printf("Machine Order:Little Endian\n");       else             printf("Machine Order:Big Endian\n");       return 0; } Method 2: int main() {      union{                    int i;                    char ch[4];      }endian={0x12345678};      if (endian.ch[0] == 0x78)           printf("Ma

Multithreading in C Tutorial - Part 5 (pthread_yield)

Calling pthread_yield api by any thread will give up the cpu to the other threads.The current thread will be placed in the end of the run queue and another thread will be scheduled by the scheduler Syntax:  int pthread_yield(void); Returns 0 on success and error value on error. Example Code: #include <stdio.h> #include <pthread.h> pthread_t tid[2]; void *thread_fn1(void *arg) { int err = pthread_yield(); perror("pthread_yield"); printf("Thread 1 in execution\n"); pthread_exit(NULL); } void *thread_fn2(void *arg) { printf("Thread 2 in execution\n"); pthread_exit(NULL); } int main() { int ret; ret = pthread_create(&tid[0], NULL, thread_fn1, NULL); if (!ret) printf("Thread[%d] created Successfully\n",1); else printf("Thread[%d] not created\n",1); ret = pthread_create(&tid[1], NULL, thread_fn2, NULL); if (!ret) printf("Thread[%d] created Successfully\n"

MultiThreading in C Tutorial - Part 4(pthread_detach)

At any point of time a thread can be in any one of the following states: joinable, detachable.By default if you are not modifying any attributes and has passed NULL as the second argument while the creation of thread(pthread_create) it will be in joinable state. Resources used by Joinable threads cannot be freed by himself, it has to freed by other threads using pthread_join.Resources used by detached threads cannot be freed by other threads,the resources are automatically freed on termination.So it is better to use pthread_detach if you are not doing any synchronization. Syntax:  int pthread_detach(pthread_t pthread); Example Code: #include <stdio.h> #include <pthread.h> void *threadFn(void *arg) { pthread_detach(pthread_self()); sleep(1); printf("Thread Fn\n"); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t tid; int ret = pthread_create(&tid, NULL, threadFn, NULL); if (ret != 0) { perror("Thread Cr

MultiThreading in C Tutorial - Part3(pthread_exit and pthread_equal)

pthread_exit: Syntax: void pthread_exit(void *retval); pthread_exit has two different roles.If it is used in the main thread,it makes it to wait until all the user level threads terminates.If it is used in a thread function it will work like a exit call. pthread_equal: Syntax: int pthread_equal(pthread_t t1, pthread_t t2); pthread_equal is used by the applications to compare two thread values.If two threads are equal, it returns a non zero value,otherwise it returns 0 Example Program: #include <stdio.h> #include <pthread.h> pthread_t tid[2]; void *thread_fn(void *arg) { if(pthread_equal(tid[0], pthread_self())) printf("Thread 0 in execution\n"); else printf("Thread 1 in execution\n"); pthread_exit(NULL); } int main() { int i; int ret; for (i = 0;i < 2;i++) { ret = pthread_create(&tid[i], NULL, thread_fn, NULL); if (!ret) printf("Thread[%d] created Successfully\n",i+1); else p

Multithreading in C Tutorial - Part 2(pthread_self)

Each thread created using pthread_create api is assigned an unique id.After the pthread_create is executed successfully,the parent can get the thread id,but what if we want to know the id of the thread while it is in execution,this can be achieved by calling a function pthread_self() Look at the example code to understand: app.c: #include <stdio.h> #include <pthread.h> void *thread_fn(void *arg) { sleep(1); printf("ID of thread in thread_fn is %u\n",pthread_self()); return NULL; } int main(int argc, char *argv[]) { pthread_t tid; printf("In Main Fn\n"); pthread_create(&tid, NULL, thread_fn, NULL); printf("ID of thread in main:%u\n",tid); pthread_join(tid, NULL); printf("After the thread execution\n"); return 0; } In order to compile this application you have to pass -lpthread as an argument to gcc gcc pthread_self.c -0 pthread_self -lpthread O/P: In Main Fn ID of thread in main:3

Process of Creating a Dynamic Library(.so) in C

Steps for creating a Dynamic Library in C Step1 : Implement source code for the library add.c:We have implemented the addition function in the file int add(int a, int b) {      return a+b; } sub.c :Implemented the subtraction function in the file int sub(int a, int b) {      return a-b; } Step2: Compile the sources into position independent relocatable  gcc -c -fpic add.c   O/P: add.o  gcc -c -fpic sub.c   O/P: sub.o Step3: As it has to be loaded into memory, we have to make it into ABI format which can be done by linker.So we will use dynamic linker and create shared object image.      gcc --shared -o libarith.so add.o sub.o Whenever we do file libarith.so ,it shows ELF it means that it can be loaded in the memory whereas the same is not true for static library image. app.c: #include <stdio.h> int main() {    printf("add:%d\t sub:%d\n".add(2,3),sub(2,3));    return 0; } Compile it with the following command: gcc app.c

Process of Creating a Static Library(.a) in C

We will see how we can create a static library in C. Now steps for creating a static library for these two files are Step1 : Implement source code for the library add.c:We have implemented the addition function in the file int add(int a, int b) {      return a+b; } sub.c :Implemented the subtraction function in the file int sub(int a, int b) {      return a-b; } Step2: Compile the sources into relocatable binaries gcc -c add.c     O/P: add.o gcc -c sub.c     O/P: sub.o Step3: Use archive tool to create a static library image ar rcs libarith.a add.o sub.o r  --> replace if existing c  --> create s  --> symbol table libarith,a is the name of the static library and the convention is the library name should start with lib. Step4: If we want to see what are the files present in the static library ar -t libarith.a    (OR) nm -s libarith.a Now the library is created, If you want to test this library you have to call the functions in your p

C Program to print odd and even numbers on different threads

#include #include #include pthread_t oddThread,evenThread; sem_t semEven,semOdd; int counter = -1; void *oddFn(void *arg) { while (counter < 15) { sem_wait(&semOdd); printf("Counter:%d\n",++counter); sem_post(&semEven); } pthread_exit(NULL); } void *evenFn(void *arg) { while (counter < 15) { sem_wait(&semEven); printf("Counter:%d\n",++counter); sem_post(&semOdd); } pthread_exit(NULL); } int main(int argc, char *argv[]) { int ret; sem_init(&semEven, 0, 1); sem_init(&semOdd, 0, 0); ret = pthread_create(&evenThread, NULL, evenFn, NULL); if (ret != 0) { perror("Error in creating Thread\n"); exit(1); } ret = pthread_create(&oddThread, NULL, oddFn, NULL); if (ret != 0) { perror("Error in creating Thread\n"); exit(1); } pthread_join(evenThread, NULL); pthread_join(oddThread, NULL); sem_destroy(&semEven); sem_destroy(&semOdd); pthread_exit(NULL);

Getting the current timestamp in C

The following program is used for getting the timestamp in C #include <stdio.h> #include <time.h> int main () {   time_t rawtime;   struct tm * timeinfo;   time ( &rawtime );   timeinfo = localtime ( &rawtime );   printf ( "Current local time and date: %s", asctime (timeinfo) );   return 0; } struct tm is defined in time.h .It has the following fields: struct tm { int tm_sec; /* Seconds (0-60) */ int tm_min; /* Minutes (0-59) */ int tm_hour; /* Hours (0-23) */ int tm_mday; /* Day of the month (1-31) */ int tm_mon; /* Month (0-11) */ int tm_year; /* Year - 1900 */ int tm_wday; /* Day of the week (0-6, Sunday = 0) */ int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */ int tm_isdst; /* Daylight saving time */ }; localtime is used to convert the information which is present in rawtime structure to structure tm.rawtime structure has the value which is equal to number of seconds elapsed

ssh without password

If you don't want type password each time you do ssh on a remote machine,then you have to generate public and private keys and copy the public keys in the remote machine ssh folder. There is a more simple way of doing this using ssh-copy-id Syntax:ssh-copy-id user@ip_addr This will do the above steps and from next time there will be no password required to enter

Multithreading in C Tutorial- Part 1

What is a Thread? Thread is a smallest sequence of instructions that can be executed independently by the scheduler.Process is nothing but multiple threads of execution running asynchronously. We will start with creating a thread in C,the API used to create a thread is pthread_create.The arguments to this function are First argument :      pthread_t *thread ,(Thread id) Second Argument: const pthread_attr_t *attr ,(Attributes if any) Third Argument: void *(*start_routine)(void *) ,(the function which should be called) Fourth Argument: void *arg,(Arguments to the function) We will see a simple example code here: #include <stdio.h> #include <pthread.h> void *ThreadFn(void *arg) { sleep(1); printf("In Thread Fn\n"); return NULL; } int main(int argc, char *argv[]) { pthread_t tid; printf("Before Thread\n"); pthread_create(&tid, NULL, ThreadFn, NULL); /*   *pthread_join blocks the calling thread until the * th

Basic OS Concepts

Context Switch: Storing the state(registers,local variables etc) of the currently running process and restoring the state of the new process is called context switch.It is nothing but switching between two processes.This operation is performed by scheduler. Starvation: It is a scenario in which a low priority process is waiting for a resource for a long time, which is acquired by the high priority process and is not released.Here the low priority process is starving for the resource. Aging:   It is a mechanism to solve the problem of starvation. Whenever any process is waiting for a long time for a resource, it will increase the priority of the resource,so that it gets the resource it is starving for. DeadLock:  It is a scenario in which two processes are waiting for a resource which is present in the other process.For example, Process P1 wants a resource R1 which is acquired by Process P2,whereas the Process P2 requires a resource R2 which is acquired by P1.So both cannot perfo

C Puzzle-2

value = a? b: c Write the code which implements the same logic without using conditional statements? Answer: value = (!!a)*b+(1-!!a)*c

C Puzzle - 1

For the following code: int fun() {      /*Write Code Here*/ } int main() {      int i=10;     fun();     printf("%d\n",  i);     return 0; } Now we have to change the value of i from 10 to 20 without changing anything in main(), we have to write all the operations in the fun() function. Logic is that local variables are stored in the stack and stack always grows in downwards. int fun() {    int j;    int *ptr=&j;    while (*ptr != 10) ptr--;    *ptr =20;     return 0; }

Look and Say Sequence Program in C

#include #include char buffer[100]="1"; char old_data[100]; void getNextNumber(void) { int i=0; char count = 49; //'1' int index = i; int buffer_index = 0; memcpy(old_data, buffer, sizeof(old_data)); memset(buffer,0,sizeof(buffer)); while(old_data[i] != '\0') { if (strlen(old_data) == 1) { buffer[buffer_index++] = old_data[0]; buffer[buffer_index++] = old_data[0]; i = 1; }else { if(old_data[index] == old_data[i+1]) count++; else { buffer[buffer_index++] = count; buffer[buffer_index++] = old_data[index]; index=i+1; count = 49; } } i++; } buffer[buffer_index] = '\0'; } int main(int argc, char *argv[]) { int count, i; printf("Enter the count\n"); scanf("%d",&count); printf("%s\n", buffer); for (i = 0;i < count - 1;i++) { getNextNumber(); printf("%s\n",buffer); } return 0; }