预期'char **'但参数类型为'char *'--argv

时间:2013-09-25 16:53:10

标签: c shell process argv

我正在尝试创建一个简单的shell,它采用“ls”或“ls -l”之类的东西并为我执行。

这是我的代码:

#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 *’

请您给我一些关于如何正确地将参数传递给我的执行函数的指示?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

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

你还需要什么?

args正在衰减到char *,但char **void execute(char **argv)

您需要将args拆分为

  • 命令
  • 选项

使用strtok功能

相关问题