2009-10-30 48 views
1

我正在編寫一個迷你shell來更熟悉C中的Unix進程管理。它從命令行讀取內容並通過execlp將這些參數傳遞給系統。strtok和execlp在迷你shell中

# 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

是否顯示「Error,command not found!」打印或不打印? – atomice 2009-10-30 17:00:59

回答

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已經發現爲什麼這是行不通的,但你沒有看到任何錯誤消息的原因是,你的shell提示符正在覆蓋它。嘗試在最後加上一個換行符:

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