C/C++ How to write shell script in Linux

In this article, we will take a look on how to write a Linux Kernel Shell Script using C/C++
First, we will take a look on the structure of a shell script program.

1.Structure of a C/C++ shell script file
For example, we will write an assignment.c shell script. The structure of the file as:

//——————————

int myTask_init(void){
}

void myTask_exit(void){
}

/*Module entry and exit points.*/
module_init(myTask_init);
module_exit(myTask_exit);

MODULE_LICENSE(“GPL”);
MODULE_DESCRIPTION(“My Task Module”);
MODULE_AUTHOR(“PrestoBear”);
//——————————
+The structure of shell script file will include the _init() method and the _exit() method. The _init() method will be run right after the shell script is loaded into the kernel. The _exit() will be run right after the script is unloaded from the kernel
+We are free to name for the init and exit methods. It is better to keep the post _init and _exit as example above
+Then, we need to declare the init and exit methods as module_init(myTask_init) and module_exit(myTask_exit);

2.Compile the file
Next, we will compile the shell script assignment.c
+We need to write a Makefile to compile for assignment.c “Click here to learn how to write Makefile
+Place the Makefile in the same folder with assignment.c, then execute the command “make”. “Click here to learn how to compile in Linux“.
+The compiler will produce several files, but we only need to focus on assignment.ko file

3.Load Linux Shell Script .ko file
dmesg -c //clear the log
sudo insmod assignment.ko //load kernel module
dmesg //show the log

4.Unload the Linux Shell Script .ko file
dmesg -c //clear the log
sudo rmmod assignment //unload the kernel module
dmesg //show the log

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.