0

I have some code below that works fine but only exits out when I do ctrl+z on Linux but not ctrl+d (EOF)? Does it have something to do with ncurses? What should I use instead (ERR?) and why?


#include <stdio.h>
#include <ncurses.h>            
#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void) 
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != EOF; i++)
    {
         if (i == (MAXLINE-1))
         {
             printf("\r\n");
             i = -1;
         }
    }

    // to close curses terminal
    endwin();
}

Thank you.

Colorful Codes
  • 577
  • 4
  • 16

2 Answers2

0

When you type Ctrl-z, the program didn't exit, only stays in background. You can see it with jobs command. You can exit the program with Ctrl-d by this code :

#include <stdio.h>
#include <ncurses.h>            
#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void) 
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != 4; i++)
    {
        if  (i == (MAXLINE-1)) {
            printf("\r\n");
            i = -1;
        }
    }

    // to close curses terminal
    endwin();
}

The change is in [(c = getch()) != 4]. The code for Ctrl-d is 4.

Philippe
  • 20,025
  • 2
  • 23
  • 32
0

"Why doesn't EOF (CTRL + D) execute in function code?"

Because you commented out the cbreak() option and with that the terminal is in raw mode.

Quotes from the Linux man pages (emphasize mine):

The raw and noraw routines place the terminal into or out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences are that in raw mode, the interrupt, quit, suspend, and flow control characters are all passed through uninterpreted, instead of generating a signal.

Source: https://linux.die.net/man/3/raw


Initially the terminal may or may not be in cbreak mode, as the mode is inherited; therefore, a program should call cbreak or nocbreak explicitly. Most interactive programs using curses set the cbreak mode. Note that cbreak overrides raw.

Source: https://linux.die.net/man/3/cbreak

As the quotes says, In raw mode the interrupt, quit, suspend, and flow control characters are passed through uninterpreted and do not generate the respective signals.

cbreak() overrides raw mode. Remove the // preceding cbreak() to uncomment cbreak() and it shall work as desired.

Beside that, you always should call either cbreak() or nocbreak() explicitly because it isn´t determined in what mode the terminal is at program startup.

Community
  • 1
  • 1