Thursday, 14 June 2012

Truth about the abundantly used printf()

If you are a beginner programmer in C, then you must have created almost every program with a printf() function, what is so important about it that we use it in most of our programs?
It provides us with visual details of what a program is outputting. It basically writes out its result onto the stdout.

But if you go through the lines submitted by the creators themselves i.e. Brian W. Kernighan and Dennis M. Ritchie, you will be shocked for a bit, but it is the truth,

"by the way, printf is not a part of the C language; there is no imput or ouput defined in C itself. printf is just a useful function from the standard library of functions that are normally accessible to C programs."

This thin, yet powerful language which is said to be portable infact is as portable as its libraries. Its libraries are its extensions which creates functionality.
There are just so many libraries available in the wild supporting all types of architectures and instrcution sets that it may appear c language is highly portable.

As this language is a major constituent for the famous unix os and the gnu/linux kernel, you can judge how powerful its functioning is. But still most of the work is done under the hood, no output to a console is made to every little syscall or connection.

This can be very easily explained by a simple example of kernel programming.
here

  

 as you can see in this, no use of printf can be seen but instead printk is used.


make file for the same is here





issue the make command to generate the neccesary executables.



 so as you can see, a kernel module has been compiled.
now lets insert our module into the kernel with insmod command. {issue sudo command if required for privilidges}


 so now even the module has been inserted succesfully, a weird questions arises, where is the output for printk()

here it is, the last line, this log can be viewed by dmesg command same thing happens when we remove our module from the kernel by issuing rmmod command, then it prints out the line in cleanup_module(),



Still for many of you there is a question that haunts you, where did the output go and why it never came up on any console screen.

in this eg, procedure of module loading and unloading is shown, this takes place several time during your reboots and shutdowns, but for most of them no output is shown, just a mere on-success statement is passed.
printf is also similar, its just for our better presentation and debugging help, in real programming it never plays any major role. This whole kernel loading thing was managed by kernel and all the outputs were logged in syslogd/klogd. So these daemons are high end designs/programs created in c, yet they dont use printf().


I hope this was of help for you. Thanks for reading. B-)

No comments:

Post a comment