force exit from readline() function

前端 未结 4 1055
遥遥无期
遥遥无期 2020-12-21 10:47

I am writing program in c++ which runs GNU readline in separate thread. When main thread is exited I need to finish the thread in which readline() function is called. The re

4条回答
  •  鱼传尺愫
    2020-12-21 11:23

    I experimented with this situation as well. I thought perhaps one could call close(STDIN_FILENO), which does cause readline to return on the other thread, but for some reason it leaves the terminal in a bad state (doesn't echo characters so you can't see what you're typing). However, a call to the 'reset' command will fix this, so the full alternative is:

    close(STDIN_FILENO);
    pthread_join(...); // or whatever to wait for thread exit
    system("reset -Q"); // -Q to avoid displaying cruft
    

    However, the final better solution I used, inspired by the other suggestions, was to override rl_getc:

    rl_getc_function = getc; // stdio's getc passes
    

    and then you can use pthread_kill() to send a signal to interrupt the getc, which returns a -1 to readline, which returns a NULL to the calling thread so you can exit cleanly instead of looping for the next input (the same as would happen if the user EOF'd by ctrl-D)

    Now you can have your cake (easy blocking readlines) and eat it too (be able to stop by external event without screwing up the terminal)

提交回复
热议问题