1

The following code behaves differently in Ubuntu 18.04 and 19.04.

In 18.04 the computer waits for input of the string as it should.

In 19.04 the computer does not wait and terminates (but shouldn't). It appears to be affected by the previous code even though it shouldn't because term was fully restored.

why ?

(note that the computer in the test running Ubuntu 19.04 is about 2x faster than the one running 18.04 although I don't think this should affect anything)

#include <termios.h>

int main(int args, char * argp[]) { 
    using namespace std;

    termios before, after;
    tcgetattr (STDIN_FILENO, &before);          
    after = before;                             
    after.c_lflag &= (~ICANON);                 
    after.c_lflag &= (~ECHO);                   
    after.c_cc[VMIN]=0;
    after.c_cc[VTIME]=0;
    tcsetattr (STDIN_FILENO, TCSANOW, &after);  
    for(;;) {
        auto ch = cin.get();
        if (ch == EOF) {
            cin.clear();
            break;
        }
    }
    tcsetattr (STDIN_FILENO, TCSANOW, &before);
    string str;
    std::getline(cin, str);
    cout << str << endl;

    return 0;
}
programmer
  • 41
  • 6
  • I see the same behavior on Fedora 30. strace shows that `std::getline` does not even attempt to read from stdin again. This is not termio-related. Something in `std::cin` makes `std::getline` bail out. Can't see why, `clear()` should be clearing the stream state. I intended to use `gdb` to step into `std::getline` to see what's up there, but, unfortunately, cannot install a matching debuginfo for my current libstdc++, 'cause it's been superceded by an update that I haven't installed yet... – Sam Varshavchik Sep 03 '19 at 03:06
  • 1
    This has something to do with `sync_with_stdio`. Adding `clearerr(stdin);`, in addition to `cin.clear()`, results in `std::getline` now blocking. I wish I could sick `gdb` onto `libstdc++`, right now, to see what it's doing... Bottom line: iostreams and file-descriptor based tomfoolery just don't jive together... – Sam Varshavchik Sep 03 '19 at 03:13
  • Thanks Sam. That solved my problem! – programmer Sep 03 '19 at 03:47

0 Answers0