2013-09-25 68 views
0

我正在尝试创建一个简单的shell,它需要类似“ls”或“ls -l”的东西并为我执行它。期望'char **',但参数的类型是'char *'--argv

这里是我的代码:

#include <stdio.h> 
#include <sys/wait.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <string.h> 
#include <sys/types.h> 

void execute(char **argv) 
{ 
    int status; 
    int pid = fork(); 
    if ((pid = fork()) <0) 
    { 
     perror("Can't fork a child process\n"); 
     exit(EXIT_FAILURE); 
    } 
    if (pid==0) 
    { 
    execvp(argv[0],argv); 
     perror("error"); 
    } 
    else 
    { 
     while(wait(&status)!=pid) 
     ; 
    } 


} 

int main (int argc, char **argv) 

{ 

    char args[256]; 
    while (1) 
    { 
     printf("shell>"); 
     fgets(args,256,stdin); 
     if (strcmp(argv[0], "exit")==0) 
      exit(EXIT_FAILURE); 
     execute(args); 
    } 

} 

我收到以下错误:

basic_shell.c: In function ‘main’: 
basic_shell.c:42: warning: passing argument 1 of ‘execute’ from incompatible pointer type 
basic_shell.c:8: note: expected ‘char **’ but argument is of type ‘char *’ 

能否请您给我介绍了如何正确传递参数给我的执行功能一些指针?

+1

每当我看到有人问一些指点我记得xkcd漫画... – streppel

回答

2

现在,您正在将一个字符串传递给​​,该字符串需要一个字符串数组。您需要将args分解为组件参数,以便​​可以正确处理它们。 strtok(3)可能是一个很好的开始。

2

note: expected ‘char **’ but argument is of type ‘char *’说全部。

你还需要什么?

args被衰减到char *,但你必须为char **void execute(char **argv)

你需要分割你的args

  • 命令
  • 选项

使用strtok功能

相关问题