2011-12-01 6 views
2

GNU Readline 라이브러리를 사용하여 쉘에서 자동 완성 및 히스토리를 구현하려고합니다. 나는 fgets()을 사용하여 사용자를 검색했으며 readline 함수가 어떻게 작동 하는지를 읽은 후에 자동 완성 등을 지원하기 위해이를 사용하기로 결정했다. 그러나 내 프로그램을 실행할 때 입력하기 전에 readline 함수가 이상한 문자를 쉘에 출력한다. 모든 입력. P�6, PJ�`, 등의 이상한 결과는 P # , P s`와 같습니다. 어떤 이유로 든 항상 P로 시작합니다. 내 코드는 다음과 같습니다.C에서 Readline 함수가 이상한 결과를 출력합니다.

int main(int argc, char* argv[]) { 

char *historic, userInput[1000]; 
static char **cmdArgv;/**The argv of the main*/ 

sa.sa_handler = handle_signal; 
sigaction(SIGINT, &sa, NULL); 
sa.sa_flags = SA_RESTART; /** Restart function incase it's interrupted by handler */ 
cmdArgv = malloc(sizeof (*cmdArgv)); 
welcomeScreen();//just printf's nothing special 
while(TRUE) 
{ 
    shellPrompt();// getcwd function 
    historic = readline(userInput); 
    if (!historic) 
     break; 
    //path autocompletion when tabulation hit 
    rl_bind_key('\t', rl_complete); 
    //adding the previous input into history 
    add_history(historic);  
    if(check_syntax(userInput) == 0){ 
     createVariable(userInput); 
    } 

    else{ 
     tokenize(cmdArgv, userInput); 
     special_chars(cmdArgv); 
     executeCommands(cmdArgv, userInput); 
    } 
} 

문제는 무엇입니까? 감사.

답변

3

초기화 userInput를 전달하기 전에 readLine()에 : 인수가 NULL 또는 경우

:이 (내가 여기 man readline를 있음) readLine() 함수에 전달 된 인수에 대한 설명입니다

memset(userInput, 0, sizeof(userInput)); 

빈 문자열이면 프롬프트가 표시되지 않습니다.

초기화하지 않았으므로 userInput은 거기에 무슨 일이 있었는지 표시했습니다.

+0

@hjmd : 감사합니다. 하지만 내 경우에 userInput을 memset해야하는 이유는 무엇입니까? readline에 관한 많은 튜토리얼을 보았습니다. – mkab

+0

@hjmd : 편집 된 답변을 보았습니다. 감사. 튜토리얼에서 언급하지 않은 이유는 아직도 나에게 당황 스럽다. – mkab

+0

필자가 보았던'sprintf()'나 그 비슷한 것들이'readLine'에 인수를 채우는 데 사용되었습니다.이 문자열은 null로 끝나는 문자열로 채워지고 의미있는 것을 표시했을 것입니다. 그 행동을 목격 할 무언가를 채워보십시오. 예를 들어,'memset()'호출 후에'userInput [0] = '$';'를하면 달러 프롬프트가 표시되어야합니다. – hmjd

관련 문제