2

I have created a digital clock program. I use this cmd

printf("\033[?25l");
            // Hiding the cursor

but when I stop the program with Ctrl+C the terminal cursor is still hidden. How do I solve this problem and restore the cursor after Ctrl+C?

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Rasathurai Karan
  • 673
  • 5
  • 16
  • 4
    Write a signal handler to unhide the cursor when ctrl-c is entered. Note that only [async safe functions](https://www.man7.org/linux/man-pages/man7/signal-safety.7.html) should be called in a signal handler and `printf` is not one of them. So you need to either use `write` or set a variable and let the main program do the `printf`. – kaylum Sep 05 '21 at 06:35
  • Another way would be not to hide the cursor but to locate it where it isn't so obviously noticed, for example at the bottom right of a frame. – Weather Vane Sep 05 '21 at 07:06
  • how can u explain by code – Rasathurai Karan Sep 05 '21 at 07:07
  • By postioning the cursor with a `gotoxy` call or terminal sequence in a similar way, before and after printing the time. The actual method would be terminal or system specific. For example on Windows I would use the API call `SetConsoleCursorPosition()`. – Weather Vane Sep 05 '21 at 07:12
  • 1
    [Catch Ctrl-C in C](https://stackoverflow.com/questions/4217037/catch-ctrl-c-in-c) – kaylum Sep 05 '21 at 07:16
  • 2
    Does this answer your question? [Catch Ctrl-C in C](https://stackoverflow.com/questions/4217037/catch-ctrl-c-in-c) – Yun Sep 05 '21 at 07:24
  • 1
    You should also unhide it when `Ctrl-Z` is pressed (i.e. also catch `SIGTSTP`) and hide it back on `SIGCONT`. And also handle `SIGTERM` similarly to `SIGINT`. It's fine to do `printf("\033[...")` to get a grip of how things work, but in general, better use `curses` which will do all that for you, and also take care of using the correct escapes for your terminal –  Sep 05 '21 at 20:47

1 Answers1

0
        static volatile int continueRunning = 1;// 
        void intHandler(int dummy) {
             printf("\033c");// clear the console
             printf("\e[?25h");//To re-enable the cursor
                 continueRunning = 0;
        }
    
    
    
    int main(int argc, char **argv) // you can use like this int main(int argc, char *argv[]) { /* ... */ }
    {
        signal(SIGINT, intHandler);
      
        
            while (continueRunning) {
/// to continuue your code
Rasathurai Karan
  • 673
  • 5
  • 16