csignalsreadline

Force readline to exit with signals


I am trying to get readline to exit when I press ctrl-c. I thought I could do this with rl_done but it is not working. Upon pressing ctrl-c I am getting these debug statements:

start readline

setting rl_done to 1

so the signal is received and rl_done set to 1 but readline does not exit for some reason.

char    **continue_input(char **input, char *str)
{
    char    *line;
    char    *temp;

    ignore_signals();
    init_signals(CONTINUE_INPUT);
    printf("start readline%c-----------%c", 10, 10);fflush(stdout); //debug
    line = readline(str);
    printf("readline ended%c-----------%c", 10, 10);fflush(stdout); //debug
    if (rl_done == 1)
    {
        rl_done = 0;
        return (NULL);
    }
    if (!line)
    {
        ignore_signals();
        init_signals(FALSE);
        return (NULL);
    }
    temp = ft_strjoin(*input, "\n");
    free(*input);
    *input = ft_strjoin(temp, line);
    free(line);
    free(temp);
    if (!input)
        exit(EXIT_FAILURE);
    ignore_signals();
    init_signals(FALSE);
    return (input);
}




void    continue_input_signal_handler(int sig)
    {
        if (sig == SIGINT)
        {
            printf("setting rl_done to 1%c-----------%c", 10, 10);fflush(stdout); //debug
            rl_done = 1;
        }
        else if (sig == SIGTERM)
        {
            exit(EXIT_SUCCESS);
        }
    }

Solution

  • your post is confusing!, and as you've not posted a minimal reproducible example, here's a trivial example of terminating on ^C for illustration only ...

    NB:(readline already handles this by default !

    #include <stdio.h>
    #include <stdlib.h>
    #include <signal.h>
    #include <readline/readline.h>
    
    void trapC()
    {
        puts("\n^c caught, terminating!");
        exit(1);
    }
    
    int main()
    {
        char *buff;
        (void) signal(SIGINT,trapC);
    
        for(;;)
        {
            buff = readline( "\nenter stuff [^C to terminate] :");
            if ( buff )
                    printf("you entered [%s]\n", buff );
            free(buff);
        }
        return(0);
    }