Question

I build a program in C, it's a console, and i use libreadline to help me build this console. Everything works fine, but when i receive an ctrl-d , i get a segmentation fault.

I can figure out how to handle this, i had tried use signal.h to do this, but don't work.

Below is a piece of my code.

int init_console(char * ip, int port) {
/** Variaveis que serão utilizadas */
char * str_command;
char * filename = malloc(100);
Client * cli = malloc(sizeof (Client));

/** Monta o filename do arquivo de histórico */
strcpy(filename, getenv("HOME"));
strcat(filename, HISTORY_FILE);

/** Inicializa o histórico de comandos */
using_history();

/** Inicializa o readline */
rl_initialize();

/** Seta o número de comandos a serem guardados */
stifle_history(10);

/** Habilita o auto completation */
rl_inhibit_completion = true;

/** Cria o arquivo de historico */
if (access(filename, F_OK) != 0) {
    /** Se  o arquivo não existe, então cria ele */
    create_history_file(filename);
} else {
    /** Le o arquivo de histórico */
    read_history(filename);
}

/** Conecta com o server */
strcpy(cli->ip, ip);
cli->port = port;

if (connect_server(cli) == CONNECT_FAILED) {
    /** Falha ao conectar, retorna erro */
    return -1;
}

/** Pega o primeiro comando */
while (true) {
    /** Pega o comando */
    str_command = readline(PROMPT);

    /** Adiciona no histórico */
    add_history(str_command);

    /** Verifica se o comando é o exit pra sair */
    if (strcmp(str_command, "exit") == 0 || strcmp(str_command, "quit") == 0) {
        /** Escreve o arquivo de histórico */
        write_history(filename);

        /** Fecha a conexão */
        close_server_connection(cli);

        /** Lib era memória */
        free(cli);

        /** Sai do loop */
        break;
    }

    /** Faz o encode */
    strcpy(cli->command, encode_command(str_command));

    /** Envia para o server */
    if (send_command(cli) == SEND_COMMAND_FAILED) {
        /** Falha ao enviar o comando */
        fprintf(stderr, "Não foi possível executar o comando\n");
    }

    /** Espera a resposta */
    if (recv_response(cli) == RECV_RESPONDE_FAILED) {
        /** Informa qual foi o erro */
        fprintf(stderr, "Não foi possível receber a resposta do socket\n");
    } else {
        /** Imprime qual foi o resultado */
        printf("%s\n", cli->response);
    }
}

return 0;

}

When i press the ctrl-d, and the program try to compare the command with "exit" or "quit", then i receive a seg fault.

Someone know how can i handle this?

Was it helpful?

Solution

You are not checking the value returned by readline. From the man page:

If EOF is encountered while reading a line, and the line is empty, NULL is returned.

So maybe check for NULL before using it ?

str_command = readline(PROMPT);
if (!str_command) {
    printf("EOF"
    /* And probably break. */
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top