Simple calculator

Within a interview they requested me to do some exercises at home and here is the question that they posed.

“Create a simple stack-based calculator. This should be capable of performing addition, subtraction, multiplication and division. Example input would be: “2*(3+1)”. The result should be expressed as a numeric value, so the example should return 8. Usage of the eval() function, although amusing, is not allowed! This test is designed to show general programming skills, rather than an understanding of the programming platform; however the solution should be demonstrated using php as the language.”

So I decided to post on this site as well the design and program that I did come up with.

Since in maths you have to equate the ( .. ) first and then * , / , + , – so to start with I created a function that will pull out the brackets from the string input

    /* need to find the brackets and then equate the value and build outwards */
    public function equate()
    {
       // this is the string that was inputted when the class was created ( $this->calcstr;)
	$theStr = $this->calcstr;
 
	$bracketI = strrpos($theStr, "(");
	// there is a bracket
	while ($bracketI >=0)
	{
	  // find a bracket to match
	  $bracketEnd = strpos($theStr, ")", $bracketI);
	  if ($bracketEnd > 0)
	  {
	    // match then get the internal bracket value
	    $EqualMiddle = substr($theStr, $bracketI+1, ($bracketEnd-$bracketI)-1);
	    $calMiddle = $this->calculateTheString($EqualMiddle);
	    // rebuild the string without the bracket but with the value
	    $theStr = substr($theStr,0, $bracketI) . $calMiddle. substr($theStr, $bracketEnd+1);
	  }
	  else
	    throw new Exception("Bracket miss matched");
 
	  $bracketI = strrpos($theStr, "(");
	  if ($bracketI == false && $theStr[0] != "(") break;
	}
	return $this->calculateTheString($theStr);
    }

So what happens is that it will find the last occurrence of a bracket “(” and then find the corresponding “)” for that bracket, error is not found. Once found, it will then send to a function called “calculateTheString” that will actually calculate the value.

The calculateTheString function

 private function calculateTheString($theStr)
    {
	// look for * / + - in that order and then get the number each side to do the math
	$mathStr = array("*", "/", "+", "-");
	foreach ($mathStr as $maths)
	{
	  do 
	  {
	    // find each occurence of the math func
	    $mathI = strpos($theStr, $maths);
	    if ($mathI > 0)
	    {
	      // find the numeric values before and after the math func
	      try {
		$valueBefore = $this->getNumbericValue(substr($theStr, 0,$mathI), 0);
		$valueAfter =  $this->getNumbericValue(substr($theStr, $mathI+1), 1);
	      } catch (Exception $ex)
	      {
		echo "Error : $ex (String = $theStr)";
	      }
	      // do the math func
	      switch($maths)
	      {
		case "*" : $newV = $valueBefore * $valueAfter; break;
		case "/" : $newV = $valueBefore / $valueAfter; break;
		case "+" : $newV =$valueBefore + $valueAfter; break;
		case "-" : $newV =$valueBefore - $valueAfter;; break;
		default : $newV =0;
	      }
	      // rebuild string without the math func that is done
	      $theStr = substr($theStr,0,($mathI-strlen($valueBefore))) . ($newV) . substr($theStr,($mathI+strlen($valueAfter)+1));
	    }
	  } while ($mathI >0);
	}
	return $theStr;
    }

will loop through the math functions (*,/,+,-) in order of calculation, if it finds one of them it will equate what the value of that block of math is e.g.

4*2+1

it would equate the 4*2 and then rebuild the string to have the result within the next loop e.g.

8+1

so that when it gets to the + math function it will add 8 to 1.

To get the number values before and after the math functions (*,/,+,-) I created a function to pull out the values called “getNumbericValue”.. since the values will either be before or after the e.g. going backwards or forwards in the string, then you will need to either go in that direction. Once you have got the area within the string of the numeric values, then use the intval to convert into a integer value. The is_numeric makes sure that there is still a numeric value present.

/* $theStr = string to search, leftOrRight means going left or right in the string, 0 = left, 1=right*/
    private function getNumbericValue($theStr, $leftOrRight=1)
    {
	if (strlen($theStr) == 0) throw new Exception("No number value");
	if ($leftOrRight ==1) { $pos =0; 
	  $start = 0;
	}else 
	{
	  $pos = strlen($theStr)-1;
	  $start = strlen($theStr) -1;
	}
 	while (true)
	{
	  if (is_numeric($theStr[$pos]))
	  {
	    if ($leftOrRight == 0) $pos--; else $pos++;
	  }
	    else break;
	}
	// if just the number at the start
	if ($pos == -1) return intval($theStr);
	// if the start is greater than the end point, change over
	if ($start > $pos) { $tmp = $pos; $pos = $start; $start = $tmp;}
	return intval(substr($theStr,$start, $pos));
    }

To build all that together with

<?php
  class calc 
  {
    private $calcstr = "";
 
    function __construct($strIn)
    {
      $this->calcstr = $strIn;
    }
 
    public function setStr($strIn = "")
    {
      $this->calcstr = $strIn;
    }
 
    /* $theStr = string to search, leftOrRight means going left or right in the string, 0 = left, 1=right*/
    private function getNumbericValue($theStr, $leftOrRight=1)
    {
	if (strlen($theStr) == 0) throw new Exception("No number value");
	if ($leftOrRight ==1) { $pos =0; 
	  $start = 0;
	}else 
	{
	  $pos = strlen($theStr)-1;
	  $start = strlen($theStr) -1;
	}
 	while (true)
	{
	  if (is_numeric($theStr[$pos]))
	  {
	    if ($leftOrRight == 0) $pos--; else $pos++;
	  }
	    else break;
	}
	// if just the number at the start
	if ($pos == -1) return intval($theStr);
	// if the start is greater than the end point, change over
	if ($start > $pos) { $tmp = $pos; $pos = $start; $start = $tmp;}
	return intval(substr($theStr,$start, $pos));
    }
 
    private function calculateTheString($theStr)
    {
	// look for * / + - in that order and then get the number each side to do the math
	$mathStr = array("*", "/", "+", "-");
	foreach ($mathStr as $maths)
	{
	  do 
	  {
	    // find each occurence of the math func
	    $mathI = strpos($theStr, $maths);
	    if ($mathI > 0)
	    {
	      // find the numeric values before and after the math func
	      try {
		$valueBefore = $this->getNumbericValue(substr($theStr, 0,$mathI), 0);
		$valueAfter =  $this->getNumbericValue(substr($theStr, $mathI+1), 1);
	      } catch (Exception $ex)
	      {
		echo "Error : $ex (String = $theStr)";
	      }
	      // do the math func
	      switch($maths)
	      {
		case "*" : $newV = $valueBefore * $valueAfter; break;
		case "/" : $newV = $valueBefore / $valueAfter; break;
		case "+" : $newV =$valueBefore + $valueAfter; break;
		case "-" : $newV =$valueBefore - $valueAfter;; break;
		default : $newV =0;
	      }
	      // rebuild string without the math func that is done
	      $theStr = substr($theStr,0,($mathI-strlen($valueBefore))) . ($newV) . substr($theStr,($mathI+strlen($valueAfter)+1));
	    }
	  } while ($mathI >0);
	}
	return $theStr;
    }
 
    /* need to find the brackets and then equate the value and build outwards */
    public function equate()
    {
	$theStr = $this->calcstr;
 
	$bracketI = strrpos($theStr, "(");
	// there is a bracket
	while ($bracketI >=0)
	{
	  // find a bracket to match
	  $bracketEnd = strpos($theStr, ")", $bracketI);
	  if ($bracketEnd > 0)
	  {
	    // match then get the internal bracket value
	    $EqualMiddle = substr($theStr, $bracketI+1, ($bracketEnd-$bracketI)-1);
	    $calMiddle = $this->calculateTheString($EqualMiddle);
	    // rebuild the string without the bracket but with the value
	    $theStr = substr($theStr,0, $bracketI) . $calMiddle. substr($theStr, $bracketEnd+1);
	  }
	  else
	    throw new Exception("Bracket miss matched");
 
	  $bracketI = strrpos($theStr, "(");
	  if ($bracketI == false && $theStr[0] != "(") break;
	}
	return $this->calculateTheString($theStr);
    }
 
  }
 
  $theequal = "2*(3+1)";
  $thecalc = new calc($theequal);
  try {
    echo $thecalc->equate();
  } catch (Exception $err)
  {	
    echo $err;
  }
?>

and the output would be

8

I found it a interesting exercise 🙂

AJAX – setup and test

AJAX is the way of communicating with a back end server without having to send the full information (you can of course) but for example you could just send a username check to see if it is available, but the main thing is that you do not send back a full page but only the part that you want to update.

With reference to the example of a username, you could just send the username and send back either yes or no response which saves allot of time and traffic from the client to the server (and makes the whole web page experience nicer).

All the AJAX is shorthand for “Asynchronous JAvascript and Xml”, asynchronous means that you can do something else whilst waiting for the response (put the kettle on and get a cup for the drink whilst the kettle is boiling) thus with javascript on the client web browser sends a request to a web page on the server with XML wrappings.

To get the basics lets start with the being

  // this function will return a XmlHttpRequest object that allows you to "talk" to the server.
  function GetXmlHttpObject()
  {
      // IE7+, FF, Chrome, Opera, Safari
      if (window.XMLHttpRequest) return new XMLHttpRequest;
 
      // IE6 , IE5
      if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  }

the GetXmlHttpObject will return a object that will allow the javascript to talk to the backend server, the newer version is call a XMLHttpRequest whilst on older browsers it was part of the ActiveXObjects.

The next is to send a request to the backend server

    xmlHttpObject.onreadystatechange=callBackFunction;
    xmlHttpObject.open("GET", GetUrl, true);
    xmlHttpObject.send(null);

The onreadystatechange, will call a function (in javascript on the client browser) when the request alters from different states, the different states are

  • 1.open method invoked successful, open a connection with the server
  • 2.server responsed with a valid header response.
  • 3.server has sent some data, the response content is started to load.
  • 4.server has finished sending all of data

so from reading the states, you are really interested in state 4, because that will have the data (server response) that you are interested in for this.

The .open forms the request to the XmlHttpRequest object to call (“GET” in HTML) the server web site, the GetUrl is just a variable that well call a php page (“ajaxbackendcall.php”) which takes a parameter called name and returns a string with the name in reverse (shall include that source code later).

And then the .send will start the ready states to change and sends the request to the backend server, here is the function that is called on the state change

  function callBackFunction()
  {
    if (xmlHttpObject.readyState == 4)
      alert(xmlHttpObject.responseText);
  }

What is happening here, is that from the state stages I am waiting on ready state to equal 4 ( when the server has finished responding) and then output the response from the responseText which is filled from the AJAX call to the backend server.

That is mainly it, here is some full code for you to try out save this as “codingfriends.com.ajax.test.html”

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html3/strict.dtd">
<html>
<head>
<script type="text/javascript">
  // the xmlHttpRequest object
  var xmlHttpObject;
 
  // the ajax call 
  function getInnerText()
  {
    // get the name to send to the server backend page
    var namehere = document.getElementById("namehere");
 
    // request the xmlHttpObject 
    xmlHttpObject = GetXmlHttpObject();
 
    // if there is not xmlHttpRequest object being allowed to be created then the browser does not support it.
    if (xmlHttpObject==null)
    {
      alert("Browser does not support XmlHttp calls e.g. AJAX");
      return;
    }
 
    // fill in the request details, e.g. the url to call and also the query string inserted into the url
    var GetUrl = "ajaxbackendcall.php"+"?name="+namehere.value;
 
    // here is the call to the server.
    // to start with setup which function to call when a ready state on the XmlHttpRequest object has changed
    xmlHttpObject.onreadystatechange=callBackFunction;
    // request the html "GET" to obtain the url (e.g. the backend server page, dynmaic normally)
    xmlHttpObject.open("GET", GetUrl, true);
    // and then issue it
    xmlHttpObject.send(null);
  }
 
  // the function that is called once the XmlHttpRequest object state has changed
  /* the readyStates are 
    1 open method invoked successful, open a connection with the server
    2 server responsed with a valid header response.
    3 server has sent some data, the response content is started to load.
    4 server has finished sending all of data
  */
  // so we listen for readyState 4 when all finished
  // and output the response text into the div id innertextoutput
  function callBackFunction()
  {
    if (xmlHttpObject.readyState == 4)
      document.getElementById("innertextoutput").innerHTML=xmlHttpObject.responseText;
  }
 
  // this function will return a XmlHttpRequest object that allows you to "talk" to the server.
  function GetXmlHttpObject()
  {
      // IE7+, FF, Chrome, Opera, Safari
      if (window.XMLHttpRequest) return new XMLHttpRequest;
 
      // IE6 , IE5
      if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  }
</script>
</head>
<body>
<a href="#" onclick="javascript:getInnerText()">click here to return text from a ajax call</a>
<br/>
Enter the name here <input id="namehere"/>
<br/>
<div id="innertextoutput"></div>
</body>
</html>

and then save this as the ajaxbackendcall.php file to call (in the same directory as the code above and also within a directory that has PHP plugin enable for that webserver be it apache or IIS.

<?php
    $name = $_GET['name'];
 
    // change the output to say something else, here I am just reversing the name
    if (strlen($name) > 0)
    {
      // have to insert something into it so that php does not make it into a array but a string
      $namereturn="0";
      $j = 0;
      for ($i = strlen($name)-1; $i >= 0; $i--)
      {
        $namereturn[$j++]=$name[$i];
      }
      echo "normal name {$name} and in reverse {$namereturn}";
    }
    else
      return "No name inputted";
?>

The output would be similar to the below. OUTPUT

click here to return text from a ajax call
Enter the name here

END OF OUTPUT

If you do not have a PHP webserver to test with, you can just alter the codingfriends.com.ajax.test.html code by altering the backend web page to call to this

var GetUrl = "nonephpbackend.html"

and create a page within the same directory as the codingfriends.com.ajax.test.html page and place something inside it like

hi there

struct – initialization values

When you define a new struct(ure) and initialize it you can use the {} to define the internals of the values within for example

typedef struct
{
    int coding;
    int friends;
} newType;
 
newType nT = { 10, 20};

so coding = 10 and friends = 20

But if you try and over initialize the values that are not present, e.g.

newType nT = { 10, 20, 30 }; // there is not place to put the 30

then the compiler will compile with

error: too many initializers for 

memcpy – copy the memory contents from one place to another

The memcpy function, does not really care about the parameters passed in, if they are the same types or of different types. Just that they are variables already declared (and of course can hold the data being passed from one place to another, because otherwise there may be a slight overlap if the copied value is larger in memory size to the copier).

So the memcpy is just a binary data copy and nothing else, there is no type checking.

Here is a example in c++ code that will copy a newly created struct(ure) from one place to another.

void* memcpy (void *copied_to, const void *copier, size_t num);

where the return is also the copied_to value, since we are not altering the copier then a const(ant) can be applied and the last parameter is num which is the size of the data you want to copy.

#include <stdio.h>
#include <string.h>
 
// diferent type of object, e.g. not a int,char
typedef struct 
{
    int bob;
} insertType;
 
int main()
{
  // create two variables of insertType with default values for bob of 10 and 20
  insertType t1 = { 10 };
  insertType t2 = { 20 };
 
  // output the declared values
  printf("t1 = %d\nt2 = %d\n", t1.bob, t2.bob);
 
  // do a memory copy of t2 into t1 only copy as big as the variable size.
  memcpy(&t1, &t2, sizeof(insertType));
 
  // output the new values
  printf("t1 = %d\nt2 = %d\n", t1.bob, t2.bob);
  return 0;
}

here is the output

t1 = 10
t2 = 20
t1 = 20
t2 = 20

also note that the size_t is a unsigned integral type (normal of int, of the base operating system)

qt – emit a signal

When you trying to link the slots and signals together you need to have a QObject::connect and also a emitting, I have created a basic demonstration of this with a QPushButton (link to qt signal and slots, and a QT link for the signal and slots)

The basics of slot(s) and signal(s) with emit(ting) is that a slot is where the emit(ed) signal goes to, when a signal is emit(ed) via a class. For example if you want to link a value changed event then you would emit a signal from within the class and then use that signal with the QObject::connect to link to a slot within class as well.

I have created a class called EmitterTest that has a function within it called

        void setValueAndEmit(int v);

this function will set the value and emit the signal for any QObject::connect to link to a slot. To emit the signal you just

        emit valueChanged(v);

where the valueChanged is the signal within the class definition (you do not define that function because it is kinder like a virtual function).

To allow for these slots and signals to be defined within the class you need to call the macro Q_OBJECT at the top of the class (within a private area) so that all of the necessary attachments to the class can be created (within the moc file associated with the class when you run the qmake later on).

To define a signal and slot there is keywords within the “new” class structure available because of the Q_OBJECT and you can just use them like public and private declarations

    public slots :
        void setValue(int v);
 
    signals:
        void valueChanged(int newV);

signals are always public in there access rights.

What the code below does is to create a slot and signal with a function that will emit a signal when called (the function that is) so the signal is “fired” off to what ever is listening to it, to connect a signal to a slot you use the QObject::connect as below

    EmitterTest em1, em2;
 
    QObject::connect(&em1, SIGNAL(valueChanged(int)),
                     &em2, SLOT(setValue(int)));

where the EmitterTest is the class that I am creating, and the object em1 signal valueChanged is linked to the same class type but different instance of it, em2 slot setValue.

Here is the code below for the full EmitterTest, here is the header file for the emitting test class, if you save as emitting.h

#ifndef EMITTING_H
#define EMITTING_H
 
#include <QObject>
 
class EmitterTest : public QObject
{
    Q_OBJECT
 
    public:
        EmitterTest() { mem_value = 0;}
 
        int getValue() const { return mem_value;}
        void setValueAndEmit(int v);
 
    // these pick up the emitted signal
    public slots :
        void setValue(int v);
 
    // these are what are sent out over emitted signals
    // you do not implement the signals since they are just virtual functions
    // as such that you call with emit then the value within the parameter(s)
    // is passed to the slot.
    signals:
        void valueChanged(int newV);
 
    private:
        int mem_value;
};
 
#endif // EMITTING_H

and here is the emitting.cpp file, that holds the main runtime main function.

#include <QObject>
#include <QString>
#include <stdio.h>
#include "emitting.h"
 
void EmitterTest::setValue(int v)
{
    // if the value has changed
    printf("The new value for %d\n", v);
    mem_value = v;
}
 
void EmitterTest::setValueAndEmit(int v)
{
    // if the value has changed
    if (v != mem_value)
    {
        mem_value = v;
        emit valueChanged(v);
    }
}
 
int main()
{
    EmitterTest em1, em2;
 
    QObject::connect(&em1, SIGNAL(valueChanged(int)),
                     &em2, SLOT(setValue(int)));
 
    em1.setValueAndEmit(10);
    printf("The connection from the object connection em1 %d should equal em2 %d \n", em1.getValue(), em2.getValue());
    em2.setValueAndEmit(15);
    printf("The connection from the object connection em1 %d should NOT equal em2 %d \n", em1.getValue(), em2.getValue());
    // the values are not the same because I have not connected them even though I have called the emit within the
    // setValueAndEmit
    return 0;
}

if you save them into a directory and then to compile you need to have the qmake and also make (nmake for windows) to make the relevant files to build a qt project. The qmake project creates the necessary .pro file to build the project, the qmake will build the necessary files (moc files) for the make (or nmake) to build the project into a executable file

qmake -project
qmake
make

and then there will be a executable file within that directory and the output will be once you have run it

The new value for 10
The connection from the object connection em1 10 should equal em2 10
The connection from the object connection em1 10 should NOT equal em2 15

as you notice since I only connected em1 signal to em2, if you change em2 mem_value then em1 does not change as well because the em2 signal is not linked back to the em1 slot.

If you get this error when you are trying out any emit test

undefined reference to `vtable for --- your class name

, it is because for some reason if you use the Q_OBJECT you need to define the class within a .h (header file) and then it will compile instead if you try and use the same .cpp for the main source code then you will get this error message.

hover over to show a hidden element

Sometimes you may not have the luxury of having javascript to do some of the great things that it can do, like showing hidden content on the screen when you hover over a HTML element (like a A HTML tag for example). In CSS you can achieve a similar result with using some of the overflow and styling elements of un/ordered lists to accomplish a similar result.

If you save this code as codingfriends_showhide.html and then open it up in Firefox or your browser of choice (not sure if it will work in IE6 shall have to check it !). and then just hover over the block and it will display the hidden message 🙂

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>CSS - show/hide on hover</title>
<style type="text/css">
/* the main ul block, there is no list style at all e.g. all together */
#showhideblock {
	list-style:none;
	margin:0;
	padding:0;
}
/* the main ul block elements push to the left and make there display inline e.g. no breaks */
#showhideblock li {
	float:left;
	width:200px;
	height:55px;
	display:inline;
	border:1px solid black; 
}
 
/* the basic showing element of the list */
#showhideblock li .show{
	display:block;
	width:200px;
	height:55px;
}
/* hide the hiding element of the list with the height of 0 and overflow set to hidden */
/* but once shown display in black */
#showhideblock li .hide {
	color : black;
	height: 0; /* hide the .hide element */
	overflow: hidden;
	background:black;
}
/* when you hover over the shown element, set the hidden element sizes */
#showhideblock li:hover .hide, #showhideblock li.over .hide {
	height: 55px;
	width:  200px;
}
/* when you hover over the shown element set the shown element height and overflow values */
#showhideblock li:hover .show, #showhideblock li.over .show {
	height: 0;
	overflow: hidden;
}
 
/* set the show a href links to colour of black (on the white background of the shown element */
/* and the textual size to be bigger than normal */
#showhideblock li a {
	color:black;
	font-size:1.5em;
}
/* since changing the background colour of the hidden element to black, change the on hover */
/* to have a textual colour of white */
#showhideblock li a:hover {
	color:white;
}
</style>
</head>
 
<body>
<ul id="showhideblock">
    <li>
      <a class="show" href="#"  title="The image to show">Hover over me, what has been hidden ?</a>
      <div class="hide">
	<a href="#" title="the hidden link">Codingfriends - I was hidden here all along</a>
      </div>
    </li>
</ul>
</body>
</html>

In essence the main parts of the code are as follows, you need to set the unordered list to have a list style of none with the list elements (li) having a display of being inline (which means that there is no breaks between the elements).

#showhideblock {
	list-style:none;
...
#showhideblock li {
	display:inline;

with this in place you can use the size of show and hide elements with also the overflow set to hidden (when you hover over the block you need to set the shown element overflow to hidden and set the size of the hidden element so that it shows)

#showhideblock li .hide {
	color : black;
	height: 0; /* hide the .hide element */
	overflow: hidden;

And once you have saved the above file and opened up in your browser of choice when you now hover over the “Hover over me” text you will see the hidden text instead.

kernel – hello world

To compile up this module you will need to have the linux header files, which should be installed but if not you just need to either use apt-get, rpm, pacman etc to install the linux header files.

With kubuntu I use the aptitude command to install applications and updates etc, but to get the linux-headers I used

aptitude install linux-headers

that is normally linked to the latest version of the linux kernel that you are using.

The main part of the program is outputting a potential parameter being passed (passing parameters to a nvidia kernel module here) and also saying hello world, kinder two for the price of one as such tutorial.

As in c language there is the printf, but in the kernel there is a printk which is the same similar thing but more for outputting errors/messages to the user.

So for example

printk(KERN_INFO "hi there\n");

the KERN_INFO is a kernel information marco that sends the details to a information level of output, e.g. /var/log/messages or you could use dmesg

here is the code on how to pull in parameters from a kernel module being loaded, the parameter_int is my parameter to be checked against and the S_IRUSR is the access rights (IR = read permission, IW = write permission, USR = user, GRP = group, OTH = others)

The module_param takes 3 parameters, the first is the variable to place the value into, second is the variable type and the third is the access rights, with the MODULE_PARM_DESC is the description of the parameter to pass, in this case it is just a integer value.

static int parameter_int = 0;
module_param(parameter_int, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(parameter_int, "An integer value");

Within a normal c/c++ program there is a main function where the program is run from, but in the kernel space since the main program is already running you can define what functions to call when the module is inserted and also removed,

module_init(hello_init);
module_exit(hello_exit);

the module_init parameter is the function to call when the module is loaded and the module_exit parameter is the function to call when module is removed from the kernel space.

Here is the full code, if you save this as helloworld_parameter.c

/* hello world with passing some parameters in the kernel module */
 
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/stat.h>
 
MODULE_LICENSE("GPL");
MODULE_AUTHOR("genux");
 
/* need to setup a setup a static variable to hold the parameter value and
   set it to a default value is none is passed */
static int parameter_int = 0;
 
/* the linux/stat.h has the S_IRUSR definitions etc.. */
/* S_IRUSR = read permission, owner
   S_IWUSR = write permission, owner
   S_IRGRP = read permission, group
   S_IROTH = read permission, others
   */
 
module_param(parameter_int, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(parameter_int, "An integer value");
 
static int __init hello_init(void)
{
	printk(KERN_INFO "Hello world\n\n");
	printk(KERN_INFO "my parameter int value is : %d\n", parameter_int);
	return 0;
}
 
static void __exit hello_exit(void)
{
	printk(KERN_INFO "Goodbye from hello world parameter\n");
}
 
module_init(hello_init);
module_exit(hello_exit);

since we are compiling a kernel module we need to link to the loaded kernel modules, here is a Makefile to compile up the program, so save this as “Makefile”

obj-m += helloworld_parameter.o
 
all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
 
clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

the first is the obj-m += which means compile a object module and you could have more than one file to compile up so use the += to add more files to it, the -C means change directory for the build environment for the kernel space, the M is a parameter passed to the build environment to use this current directory for where the source files are, and the modules means to create kernel modules e.g. filename.ko.

once you have run the

make

there should be a file called helloworld_parameter.ko, to find out details about your new module you can use the modinfo

modinfo helloworld_parameter.ko
filename:       helloworld_parameter.ko
author:         genux
license:        GPL
srcversion:     A81F18D40DA3C5FAB1C71FF
depends:
vermagic:       2.6.31-17-generic SMP mod_unload modversions
parm:           parameter_int:An interger value (int)

and the parm: is the important part here, it is what the parameter is called to pass a value to for example to watch the module being inserted if you open up two consoles and on one put

tail -f /var/log/messages

in the second console do

insmod helloworld_parameter.ko
rmmod helloworld_parameter.ko
insmod helloworld_parameter.ko parameter_int=3
rmmod helloworld_parameter.ko

and the output should be in the first console

Hello world
 
my parameter int value is : 0
Goodbye from hello world parameter
 
Hello world
 
my parameter int value is : 3
Goodbye from hello world parameter

hope that helps with kernel modules, I am planning on doing a kernel module for a custom built USB device.