how to handle Ctrl+D using GNU Readline

860 Views Asked by At

I'm trying to read a line from stdin using the GNU Readline Library. I have two major problems (I think): one is the PROMPT and the other one is handling Crtl+D (which is supposed to exit the minishell, but seg faults instead) How can I handle Ctrl+D so that it can exit? This is the code where I use readline() functions:

char* readl(char* line){
    char* string="";
    char* pitos="";
    pitos=getenv("USER");
        strcat(pitos,PROMPT);
        strcat(pitos," ");
    while(strcmp(string,"")==0){


        //printf("%s%s ",getenv("USER"),PROMPT);
        string = readline (pitos);
    }
    if(!string){ #trying to exit when ctrld
        exit(0);
    }else{
        char* com = strchr(string,'#'); #ignore comments
        if(com!=NULL){
            *com=NULL;
        }
        add_history(string);
        strcpy(line,string);
        return string;
    }
}
2

There are 2 best solutions below

1
On

One problem appears to be that you call strcmp() on the result of readline() before testing it for NULL.

Try this:

while(string && strcmp(string,"")==0){
    ...
0
On
char* pitos="";
pitos=getenv("USER");
    strcat(pitos,PROMPT);
    strcat(pitos," ");

There is just 1-byte available in the string pointed to by pitos (the terminating '\0'), and it is undefined behavior to write to it.