2009-10-30 4 views
1

나는 C의 유닉스 프로세스 관리에 익숙해지기 위해 미니 쉘을 작성하고있다. 명령 행에서 내용을 읽고 execlp를 통해이 인수를 시스템에 전달한다. 미니 쉘에서 strtok과 execlp

# include <stdio.h> 
# include <stdlib.h> 
# include <unistd.h> 

#define MAXSIZE 100 

char prompt[MAXSIZE]; 

int main(void) 
{ 
    pid_t pid; 

    printf("> "); 

    // read stuff 
    if (fgets(prompt, MAXSIZE, stdin) == NULL){ 
     printf("Input validation error!"); 
     abort(); 
    } 
    // printf("DEBUG: %s" , prompt); 

    if (strcmp(prompt, "exit")==0) abort(); 


    if ((pid=fork())<0){  // copy process 

     printf("Process error!"); 
     abort(); 
    } 

    if (pid==0){    // exec in son-prcess 

     char *command=(char*)strtok(prompt, " "); 
     execlp(command, command, 0); // overwrite memory 

     printf("Error, command not found!"); 
     abort(); 
    } else { 

     waitpid(pid, 0, 0); 
    } 
} 

는 사실이 그것을 것입니다,하지만 난 execlp()에서 출력을하지 않습니다. 그 이유를 아는 사람이 있습니까?

+0

"오류, 명령을 찾을 수 없습니다!" 인쇄 되든 안되니? – atomice

답변

4

command\n (개행)이 포함되어있어 프로그램 실행을 시도했지만 실패했습니다. 나는 strtok에 ""대신에 \n을 넣은 다음 성공적으로 실행했습니다. 상세

:

if (pid==0){    // exec in son-prcess 
     char *command=(char*)strtok(prompt, "\n"); 
     printf ("'%s'\n", command); 
     execlp (command, command, 0); // overwrite memory 
     printf("Error %d (%s)\n", errno, strerror (errno)); 
     abort(); 
    } else { 

테스트 실행 : 작동하지 않는 이유

 
$ ./a.out 
> ls 
'ls' 
(usual ls behaviour) 
1

Kinopiko 이미 찾았지만, 어떤 오류 메시지가 표시되지 않은 이유는 당신의 쉘 프롬프트이다 그것을 덮어 씁니다. 끝 부분에 줄 바꾸기를 시도하십시오.

printf("Error, command not found!\n");