Gingerbeer
Gingerbeer

Reputation: 1

Pressing ENTER constantly in an EOF loop alternative

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?

Upvotes: 0

Views: 141

Answers (1)

Buddhima Gamlath
Buddhima Gamlath

Reputation: 2328

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));
   }
}

Upvotes: 3

Related Questions