WATCHDOG

WATCHDOG

INTRODUCTION

For those embedded systems that can’t be constantly watched by a human, watchdog timers may be the solution.

The watchdog timer is an important device in the embedded system , which is used to develop reliable products. Most of the embedded systems need to be self-reliant in order to restart and restore the system if any software bug disturbs the system. It is not always possible for human operators to wait for rebooting the system for every software problem. The watchdog timer is a piece of hardware that provides ultimate solutions for the real-time industries, which used to detect system abnormalities automatically and to reset the processor.

attiny10-blinker_yamaguchi_flash

 

 

Watchdog Timers(WDT)

A watchdog timer is a piece of hardware that can be used to automatically detect software anomalies and reset the processor if any occur. Generally speaking, a watchdog timer is based on a counter that counts down from some initial value to zero. The embedded software selects the counter’s initial value and periodically restarts it. If the counter ever reaches zero before the software restarts it, the software is presumed to be malfunctioning and the processor’s reset signal is asserted. The processor (and the embedded software it’s running) will be restarted as if a human operator had cycled the power.

Figure 1 shows a typical arrangement. As shown, the watchdog timer is a chip external to the processor. However, it could also be included within the same chip as the CPU. This is done in many micro-controllers. In either case, the output from the watchdog timer is tied directly to the processor’s reset signal.

image1

kicking the dog

The process of restarting the watchdog timer’s counter is sometimes called “kicking the dog.” The appropriate visual metaphor is that of a man being attacked by a vicious dog. If he keeps kicking the dog, it can’t ever bite him. But he must keep kicking the dog at regular intervals to avoid a bite. Similarly, the software must restart the watchdog timer at a regular rate, or risk being restarted.

Advantage of Watchdog Timers:

  • Resets automatically without human intervention.

  • Detects the errors in the program and reboot the system

  • Cost sensitive

  • Saves the time and money

  • No need to place the employers to monitor the software debugs.

  • Increases the system performance.

SUMMARY

A number of considerations must go into any design that uses a watchdog as a monitor. Once the timeout period is determined, the system software must be analyzed to determine where to locate the watchdog restart instructions. For an effective design, the number of watchdog restarts should be kept to a minimum, and some consideration should be given to the likelihood of incorrectly executing a restart. As mentioned previously, some system software is too convoluted or data-dependent to ensure that all software flow paths are covered by a watchdog restart. This may dictate that a self-diagnostic software approach might be required. If there is an expected failure mechanism such as a periodic EMI burst or power supply glitch, the watchdog timeout should consider this period.

 

 

Pushpraj Kumar 🙂

Advertisements

MySQL C – API programming

MySQL C – API programming

MySQL is a leading open source database management system. It is a multi user, multithreaded database management system. MySQL is especially popular on the web.

Basic Structure of C Programs that uses MySQL C mysqlwithcAPI 1. All programs must include <mysql/mysql.h> as the last include.2. Define MYSQL type variable. NOTE: THERE CAN BE ONLY ONE MYSQL VARIABLE.3. Initialize MYSQL type variable with mysql_init()4. Load any options, if required, by using mysql_options(). If you don’t need don’t call. You can call this fuction multiple times if you require. If you call this, call this before mysql_real_connect() and after mysql_init().5. Connect by calling mysql_real_connect()6. Call the business logic and MySQL API’s7. Close the MYSQL type variable.

 

Template of program

#include <mysql/mysql.h><return_type> <function_name>(parameters)

{

MYSQL mysql; mysql_init(&mysql);

mysql_options(&mysql,MYSQL_OPT_COMPRESS,0);      

/*call only if required otherwise omit*/

mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,”Pushpraj”);        

 /*call only if required otherwise omit*/

mysql_real_connect(….);      

/* now call other API’s*/

mysql_close(&mysql);

}

 Compiling and Running in UNIX :- 

To Compile :-  $gcc mysql_app.c -o mysql_app -I/usr/local/include -L/usr/local/lib/mysql –lmysqlclient

To Run :-  $./mysql_app

Examples:-

1. Test the connection.

#include </usr/include/mysql/my_global.h>

#include </usr/include/mysql/mysql.h>

int main(int argc, char **argv)

{

printf(“MySQL client version: %s\n”, mysql_get_client_info());

  exit(0);

}

Description:-  “mysql_get_client_info()”, this mysql function collects the version information of mysql.

2. Create table and insert data into table.

#include <my_global.h>

#include <mysql.h>

void finish_with_error(MYSQL *con){

  fprintf(stderr, “%s\n”, mysql_error(con));

  mysql_close(con);

  exit(1);       

}

 

int main(int argc, char **argv)

{

  MYSQL *con = mysql_init(NULL);

  if (con == NULL) {

      fprintf(stderr, “%s\n”, mysql_error(con));

      exit(1);

  } 

if (mysql_real_connect(con, “192.168.2.50”, “username”, “password”,”db-Name”, port-No, NULL, 0) == NULL)

  {

      finish_with_error(con);

  }   

 

  if (mysql_query(con, “DROP TABLE IF EXISTS Dell”)) {

      finish_with_error(con);

  }

  if (mysql_query(con, “CREATE TABLE Dell(Id INT, Name TEXT, Price INT)”)) {     

      finish_with_error(con);

  }

  if (mysql_query(con, “INSERT INTO Dell VALUES(1,’vostro14′,26042)”)) {

      finish_with_error(con);

  }

  if (mysql_query(con, “INSERT INTO Dell VALUES(2,’inspiron15′,37000)”)) {

      finish_with_error(con);

  }

  if (mysql_query(con, “INSERT INTO Dell VALUES(3,’inspiron16′,40000)”)) {

      finish_with_error(con);

  }

  if (mysql_query(con, “INSERT INTO Dell VALUES(4,’ vostro15′,29000)”)) {

      finish_with_error(con);

  }

  if (mysql_query(con, “INSERT INTO Dell VALUES(5,’express’,69000)”)) {

      finish_with_error(con);

  }

  mysql_close(con);

  exit(0);

}

Description:- mysql_init, allocates/intialises a Mysql object suitable for mysql_real_connect()establishes a connection to the database.We provide connection handler, host name, username ,password ,database name, port number , unix socket and client flag.

3. Create connection with Database & fetch the records.

#include <my_global.h>

#include <mysql.h>

void finish_with_error(MYSQL *con)

{

  fprintf(stderr, “%s\n”, mysql_error(con));

  mysql_close(con);

  exit(1);       

}

int main(int argc, char **argv)

{     

  MYSQL *con = mysql_init(NULL);

  if (con == NULL)

  {

      fprintf(stderr, “mysql_init() failed\n”);

      exit(1);

  } 

 

  if (mysql_real_connect(con, “192.168.2.50”, “username”, “password”,”db-Name”, port-No, NULL, 0) == NULL)

  {      finish_with_error(con);  }  

 

  if (mysql_query(con, “SELECT * FROM Dell”))

  {      finish_with_error(con);  }  

  MYSQL_RES *result = mysql_store_result(con);

  if (result == NULL)

  {      finish_with_error(con);  }  

  int num_fields = mysql_num_fields(result);

  MYSQL_ROW row;

  while ((row = mysql_fetch_row(result)))

  {

      for(int i = 0; i < num_fields; i++)

      {

          printf(“%s “, row[i] ? row[i] : “NULL”);

      }

      printf(“\n”);

  }

  mysql_free_result(result);

  mysql_close(con);

  exit(0);

}

Description:-

  • Create a connection:: mysql_real_connect(con, “192.168.2.50”, “username”, “password”,”db-Name”, port-No, NULL, 0)
  • Execute query:: mysql_query(con, “SELECT * FROM Dell”)
  • Get the result set:: MYSQL_RES *result = mysql_store_result(con)
  • Fetch all available rows one by one :: row = mysql_fetch_row(result)
  • Free the result set:: mysql_free_result(result)
  • Close the connection:: mysql_close(con);

Thanks

Pushpraj Kumar

Reason for “glibc – detected” and the possible cause.

Most common reason for glibc – detected:-

  • When we are trying to free some memory  which is logically not available for “free ()” .
  • When we are trying to free some memory which is already free.
  • When we are trying to use multiple “free()”  for the same variable.
  • When we are trying to free pointers.
  • When we are trying to free the variable from outside the scope of variable.
  • Using an uninitialized pointer.
  • Writing outside your array bounds.

To avoid or solve glibc detection follows some basic and common rule:-

  1.    Set pointer to NULL after free
  2.    Check for NULL before freeing.
  3.     Initialize pointer to NULL in the start.
  4.    Always allocate storage blocks with calloc or some other means of initializing every block to known all-zeros.
  5.    Write test-scripts to independently exercise all major pieces of the program in isolation to the others. Run these tests all the time to catch regressions.
  6.    Use debugging-tools that add “eyecatchers” around storage-blocks to detect “off-by-one” overwrites and other similar problems. Consider leaving them in, in the production(!) code.

Example:-

int main()

{

char* s = (char*) malloc(sizeof(char)*10);

s=”hello”;

free(s);

}

Here we get  “** glibc detected *** free(): invalid pointer: 0x0000000000400b2c”

Solution-        s=”hello”;

Here we are assigning another address to s, to a statically allocated memory. Freeing it is not correct. Also, since we are doing this, we are basically leaking the memory you have allocated here:

.                     char* s =(char*) malloc(sizeof(char)*10);

#include <stdio.h>

#include <string.h>

#include<stdlib.h>

int main(){

static const size_t kBufferSize = 10;

char* s = (char*)malloc(sizeof(char)*kBufferSize);

strncpy(s,”hello”, kBufferSize); // better than strcpy, you are protecting

// yourself from a buffer overflow

free(s);

}

 

ImageHOW TO CREATE LOCK FILE IN C

File locking provides a very simple yet incredibly useful mechanism for coordinating file accesses. Before I begin to lay out the details, let me fill you in on some file locking secrets:-

There are two types of locking mechanisms: mandatory and advisory.

è Mandatory systems will actually prevent read() and write() to file.

è There are two types of (advisory!) locks:              read locks and write locks (also referred to as shared locks and exclusive locks, respectively.)

Here I am demonstrating READ-LOCK …

In  my  case , I want  to reduce CPU usage which  takes very  high CPU usage % in case of accessing Sqlite3  by  two  application simultaneously.

To solve  this problem  I  applied  lock  file  concept  to synchronies  applications ,

I applied it for three different applications.

Steps followed while creating lock file:-

è Finalize  File Name (xyz.lock)

è Finalize  lock file  location

è Before running  application , check lock file is  present or not

if(getlock(lockfile)== 1) :: Lock file is not present

è If lock file is not present  then create  lock file

int lockstatus = setlock(lockfile);

è After  completion  of job  delete lock file

Removelock (lockfile)

è If  lock file is  present  then sleep  for  sometime then again check for lock file

è While creating lock file, handle unexpected application closing mechanism to avoid trouble when next time application needs to be run.

Note: Extension of lock file is (abc.lock)

Note: Remove lock file when application is forcefully terminating (ctrl + C)

(Example of lock file in c using semaphores : –  )

Reference: http://www.c-program-example.com/2012/04/c-program-to-lock-file-using-semaphores.html

PUSHPRAJ  KUMAR..(pushpraj@helicaltech.com)