0

I'm new to programming, so bear with me. Also using GNU/Linux.

So I'm trying to create a loop that will check if I have used CTRL+D to end the loop to a MySQL connection, but at the same time constantly check the connection to the server.

while ((c = getchar()) != EOF)
{
    if (mysql_ping(conn) == 1)
    {
        fprintf(stderr, "Error: %s\n", mysql_error(conn));
    }
}

A problem is that I constantly have to press ENTER to check if the connection is still alive, however I want it to automatically check the connection to the MySQL server while still having the EOF feature so people can close the connection.

I know why this is happening, I'm just not sure how to fix it. Are there any other inbuilt functions or possible external libraries that I require?

superM
  • 8,605
  • 8
  • 42
  • 51
  • 3
    What you need is a non-blocking check. Possible duplicate: http://stackoverflow.com/questions/11472043/non-blocking-getch – Wintermute Dec 23 '13 at 09:43

1 Answers1

3

The problem is getchar() being a blocking function. That means, whenever you call getchar(), it waits until a key is pressed.

Try something like this.

For linux... You need to install ncurses library.

 #include <curses.h> 

 ...

 int key;
 nodelay(stdscr, TRUE);
 while (1) {
      if ((key = getch()) == ERR) {  // no key is pressed...
        if(mysql_ping(conn) == 1){
          fprintf(stderr, "Error: %s\n", mysql_error(conn));
        }
      }else { // key is pressed...
          if (key == EOF) break;
      }
 }

For windows...

#include <conio.h>

...


while(1){
   if (_kbhit()){
      int key = _getch();
      if (key == EOF) break;
   } 
   if(mysql_ping(conn) == 1){
     fprintf(stderr, "Error: %s\n", mysql_error(conn));
   }
}
Buddhima Gamlath
  • 2,318
  • 1
  • 16
  • 26