2009-10-30 19 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");