This short article is on request of my friend Viswanath who wanted to run a C program without main() function on his computer .
I have done this on Ubuntu OS , with the simple Linux module , taken form guide :
"The Linux Kernel Module Programming Guide"
note : Aim of this article is not to teach you how to write a Linux kernel module , but to simply write a C program which runs on your Linux system and prints "Hello world", without use of main() function
only thing worth mentioning is "output" from "printk" goes to by default "/var/log/messages" , so your "hello world" would be printed their instead of terminal.
Step 1 :
create a file named hello-1.c with code given below :
* hello−1.c − The simplest kernel module.
printk(KERN_INFO "Hello world 1.\n");
* A non 0 return means init_module failed; module can't be loaded.
printk(KERN_INFO "Goodbye world 1.\n");
//code ends here
Step 2 :
create a Makefile , with following code : (ie a file name Makefile )
//code starts here
obj-m += hello-1.o
//code ends here
from terminal with sudo premission run following command :
you will see output like given below if successful :
make −C /lib/modules/2.6.11/build M=/root/lkmpg−examples/02−HelloWorld modules
make: Entering directory `/usr/src/linux−2.6.11'
CC [M] /root/lkmpg−examples/02−HelloWorld/hello−1.o
Building modules, stage 2.
LD [M] /root/lkmpg−examples/02−HelloWorld/hello−1.ko
make: Leaving directory `/usr/src/linux−2.6.11'
to load your module run command :
$ insmod ./hello-1.ko
now your module should be added in the module list of kernel. For checking this type following command :
$ cat /proc/modules
the first entry should be hello-1 , and thats your module.
to unload your module use following command :
$ rmmod hello-1
Step 6 :
wondering where did your printk " Hello world 1." and " Goodbye world 1."
went just and check the file :
$ cat /var/log/messages
towards the end you will find the two entries ,
Hello world 1.
Goodbye world 1.
Thanx for reading.
Note: if you really want to understand how all this worked please go through the article "The Linux Kernel Module Programming Guide" , which is easily available on web.