c

时间:2017-02-28 14:35:47

标签: c shell warnings

我想创建一个命令行解释器,每行有多个comamnd。 我将从keybord命令输入,例如:pwd ; ls ; cat file ; ls -l

我写了这个,有人可以帮我警告吗?

警告:

ex.c: In function ‘Execute’:

ex.c:33:18: warning: passing argument 1 of ‘execvp’ from incompatible pointer type [-Wincompatible-pointer-types]
        if(execvp(cmd, pin) == -1) {

In file included from ex.c:3:0:

/usr/include/unistd.h:581:12: note: expected ‘const char *’ but argument is of type ‘char **’
 extern int execvp (const char *__file, char *const __argv[])


ex.c: In function ‘main’:

ex.c:105:17: warning: passing argument 1 of ‘Execute’ from incompatible pointer type [-Wincompatible-pointer-types]

         Execute(pin[0],pin);


ex.c:21:6: note: expected ‘char **’ but argument is of type ‘char *’
 void Execute(char* cmd[],char* pin[]) {
      ^~~~~~~

抱歉英文不好。

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

#define MAX_SIZE 512

//Clean function
void Clean(char* cmd[],char* pin[]) {          //Clean Array

    int a;
    for(a=0; a < 40; a++){
            cmd[a] = NULL;
            pin[a] = NULL;
    }        
}

//execute commands 

void Execute(char* cmd[],char* pin[]) { 

    pid_t pid;
    pid = fork();    

    switch(pid) {
        case -1:  
          printf("DEBUG:Fork Failure\n");
          exit(-1);
        case  0:
          execvp(*cmd, pin);

          if(execvp(cmd, pin) == -1) {
                printf("Command Not Found\n");
                exit(0);
          }

        default:  
        wait(NULL);
        printf("DEBUG:Child Finished\n");    
    }
}

int main() {
    char* cnd;
    char* cmd[40];
    char* pin[40];
    char* array;
    int how_much;

    char *input = malloc (MAX_SIZE);

    if (input == NULL) {
        printf ("No memory\n");
        return 1;
    }

    Clean(cmd,pin);

    printf("shell> ");

    fgets (input, MAX_SIZE, stdin);

    if ((strlen(input)>0) && (input[strlen (input) - 1] == '\n')) {
        input[strlen (input) - 1] = '\0';
    }

    printf("INPUT: %s\n", input);

//searching for ";"

    cnd = strtok(input, ";");

    int i = 0;

    while(cnd != NULL) {    
        cmd[i] = cnd;
        i++;
        cnd = strtok(NULL, ";");
    }

    cmd[i] = NULL;
    how_much = i;

// searching for " "    

    for(int j=0; j < how_much; j++) {            
        array = strtok(input, " ");

        int k=0;

        while(array != NULL) {  
            pin[k] = array;
            k++;
            array = strtok(NULL, " ");
        }

        pin[k] = NULL;

        Execute(pin[0],pin);
    }

    free (input);

   return 1;
}

1 个答案:

答案 0 :(得分:0)

Execute函数中:

...
case  0:
  execvp(*cmd, pin);

  if (execvp(cmd, pin) == -1) {
  ...

您首先execvp(*cmd, pin)然后execvp(cmd, pin)。 这是否应该表明你出了什么问题。

在这里:

Execute(pin[0],pin);

在第一个参数中Execute需要char*数组,但您提供的是char*

可能存在更多问题。