Hello Guys I am Vineet at EPRA bringing to you my third blog entry also based on constructors and destructors in C. You may think why so much of the constructor and destructor stuff in the last 3 classes. But you must realize that Linux Kernel is Object-Oriented (OO) and Device Drivers are nothing but Objects so one must be familiar with OO concepts at the beginning itself. Also with constructors and destructors we learn imp concepts such as priority of tasks which is a highly important feature of operating systems.

Sample Code: –

#include <stdio.h>

void cons1() __attribute__((constructor (101)));
void des1() __attribute__((destructor (101)));

void cons2() __attribute__((constructor (102)));
void des2() __attribute__((destructor (102)));

void cons3() __attribute__((constructor (103)));
void des3() __attribute__((destructor (103)));

int main (void)
{
printf (“\nInside main ()”);
}

void cons1()
{
printf (“\nIn constructor_1()”);
}

void des1()
{
printf (“\nIn destructor_1 ()”);
}

void cons2()
{
printf (“\nIn constructor_2()”);
}

void des2()
{
printf (“\nIn destructor_2()”);
}

void cons3()
{
printf (“\nIn constructor_3()”);
}

void des3()
{
printf (“\nIn destructor_3()”);
}

In the above code example what we have done is we have implemented 3 constructors and their corresponding destructors with priorities 101,102,103.(Priorities 1 to 100 are reserved for other default constructors.)As you would have expected the constructors with priorities 101,102 and 103 will run in succession. But the real Q is what about the destructors?

Well the ouput of the above program would be :-

In constructor_1()

In constructor_2()

In constructor_3()

Inside main

In destructor_3()

In destructor_2()

In destructor_1()

While the flow of the sequence of constructors is according to the assigned priorities the flow of sequence for the destructors is opposite. The reason for this is CRT(C RUNTime) first creates objects of lower priorities(101,102,103) and then destruct them in reverse order(103,102,101). The object which is created last will be destroyed first ie. a stack structure of implementation.

If you have any further queries feel free to post.