Home > Software design >  How to implement a fsm
How to implement a fsm

Time:11-03

I want to parse output from a commandline tool using the fsm programming model. What is the simplest implementation of a fsm that is possible for this task?

CodePudding user response:

The fsm model works in C by assigning function pointers to certain functions that have to process certain data. One good use for fsms is for parsing commandline arguments, for parsing captured output.... The function pointer is assigned to a preset starting function. The start function assigns the function pointer, which must be passed along, to the appropriate next function. And that decides the next function and so on. Here is a very simple implementation of a fsm:

struct _fsm
{
    void (*ptr_to_fsm)(struct _fsm fsm);
    char *data;
}

struct _fsm fsm;
fsm->ptr_to_fsm = start; // There is a function called start.
while (fsm->ptr_to_fsm != NULL)
{
    fsm->ptr_to_fsm(&fsm);
}

void start (struct _fsm fsm)
{
    if (fsm->data == NULL)
    {
         fsm->ptr_to_fsm = stop; // There is a function called stop.
    }
    /* Check more more conditions, and branch out on other functions based on the results. */
    return;
}

void stop (struct _fsm fsm)
{ 
   fsm->ptr_to_fsm = NULL; /* The while loop will terminate. */
   /* And you're done (unless you have to do free`ing. */
}

CodePudding user response:

Basically, the core idea of a finite state machine is that the machine is in a "state" and, for every state, the behaviour of the machine is different from other states.

A simple way to do this is to have an integer variable (or an enum) which stores the status, and a switch() statement which implements, for every case, the required logic.

Suppose you have a file of the followin kind:

something
begin
  something
  something2
end
something

and you duty is to print the part between begin/end. You read the file line by line, and switch state basing on the content of the line:

// pseudo-C code
enum state {nothing, inblock};
enum state status;
string line;

status = nothing;

while (!eof(file)) {
  readline(line);
  switch(status) {
    case nothing:
      if (line == "begin") status=inblock;
      break;
    case inblock:
      if (line == "end")
        status=nothing;
        else print(line);
      break;
  }
}

In this example, only the core idea is shown: a "status" of the machine and a mean to change status (the "line" read from file). In real life examples probably there are more variables to keep more informations for every state and, perhaps, the "status" of the machine can be stored in a function pointer, to avoid the burden and rigidity of the switch() statement but, even so, the programming paradigm is clean and powerful.

  • Related