2.4. Hello World (part 3): The __init and __exit Macros

This demonstrates a feature of kernel 2.2 and later. Notice the change in the definitions of the init and cleanup functions. The __init macro causes the init function to be discarded and its memory freed once the init function finishes for built-in drivers, but not loadable modules. If you think about when the init function is invoked, this makes perfect sense.

There is also an __initdata which works similarly to __init but for init variables rather than functions.

The __exit macro causes the omission of the function when the module is built into the kernel, and like __exit, has no effect for loadable modules. Again, if you consider when the cleanup function runs, this makes complete sense; built-in drivers don't need a cleanup function, while loadable modules do.

These macros are defined in linux/init.h and serve to free up kernel memory. When you boot your kernel and see something like Freeing unused kernel memory: 236k freed, this is precisely what the kernel is freeing.

Example 2-5. hello-3.c

/* a1387.htm a1387.html a1403.htm a1403.html book1.htm c1050.htm c1050.html c1159.htm c1159.html c119.htm c119.html c1209.htm c1209.html c1254.htm c1324.htm c1324.html c1350.htm c1350.html c38.htm c38.html c425.htm c425.html c567.htm c567.html c708.htm c708.html c885.htm c885.html c890.htm c890.html c976.htm c976.html doc-index.html f25.htm f25.html figures hello2.html i1413.htm index.html interrupthandlers.html ln16.html TXT_lkmpg.html x1052.html x1161.html x1194.htm x1194.html x1211.html x121.html x1256.html x1326.html x1352.html x1389.html x1405.html x181.htm x181.html x217.htm x245.htm x245.html x279.htm x279.html x27.html x30.htm x30.html x323.htm x323.html x351.htm x351.html x35.htm x35.html x380.htm x380.html x40.html x427.html x44.htm x44.html x569.html x710.html x769.htm x769.html x810.htm x810.html x861.htm x861.html x887.html x892.html x978.html hello-3.c - Illustrating the __init, __initdata and __exit macros. figures/ #include <linux/module.h> /apps /backup /bin /boot /data /dev /etc /home /lib /lost+found /media /misc /mnt /net /opt /proc /root /sbin /selinux /srv /sys /tftpboot /tmp /usr /var Needed by all modules figures/ #include <linux/kernel.h> /apps /backup /bin /boot /data /dev /etc /home /lib /lost+found /media /misc /mnt /net /opt /proc /root /sbin /selinux /srv /sys /tftpboot /tmp /usr /var Needed for KERN_INFO figures/ #include <linux/init.h> /apps /backup /bin /boot /data /dev /etc /home /lib /lost+found /media /misc /mnt /net /opt /proc /root /sbin /selinux /srv /sys /tftpboot /tmp /usr /var Needed for the macros figures/ static int hello3_data __initdata = 3; static int __init hello_3_init(void) { printk(KERN_INFO "Hello, world %d\n", hello3_data); return 0; } static void __exit hello_3_exit(void) { printk(KERN_INFO "Goodbye, world 3\n"); } module_init(hello_3_init); module_exit(hello_3_exit);