读取多个命令传递给execvp()

时间:2016-09-17 16:38:40

标签: c linux shell parsing

我正在编写一个创建一个小shell的代码。我无法尝试让我的代码读取多个命令。每个命令由&#34 ;;"分隔。字符。例如,如果我运行我的代码并输入" ls -l; LS"这两个命令都能正常工作。但是,如果我做类似" ls; ls -l"它不会执行ls -l。我相信我的错误是我如何读取命令,但我不确定。以下是我的代码。

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

 #define MAX_CHARACTERS 512

int commandSplit(char *c, char *a[], int t[]) {

int count = 0;
int total = 0;
char *temp[MAX_CHARACTERS];
char *readCommands = strtok(c, ";");
while(readCommands != NULL) {
    printf("Reading full command: %s\n", readCommands);
    temp[count] = readCommands;
    count++;
    readCommands = strtok(NULL, ";");
}
for(int i = 0; i  < count; i++) {
    char *read = strtok(temp[i], " ");
    int track = 0;
    while(read != NULL) {
        printf("Individual command w/ %i chars: %s\n", (int)strlen(read), read);
        a[total] = read;
        printf("a[%i] = %s\n", total, a[total]);
        track++;
        total++;
        read = strtok(NULL, " ");
    }
    t[i] = track;
}

return count;
}

int main() {

int exitProgram = 0;
char *args[MAX_CHARACTERS];

while(!exitProgram) {

char *commands = (char *)(malloc(MAX_CHARACTERS*sizeof(char)));
int tracker[MAX_CHARACTERS];
int numOfCommands = 0;
printf("tinyshell>");
fgets(commands, MAX_CHARACTERS, stdin);
int len;
len = strlen(commands);
if (len > 0 && commands[len-1] == '\n') {
    commands[len-1] = '\0';
}
if(len > MAX_CHARACTERS) {
    printf("TOO MANY CHARACTERS - MAX: 512\n");
    continue;
}

if(strlen(commands) == 0) continue;

numOfCommands = commandSplit(commands, args, tracker);

if(strcmp(args[0], "quit") == 0) {
    printf("Reached an exit1\n");
    exitProgram = 1;
    continue;
}

printf("Tracker is: ");
for(int i = 0; i < numOfCommands; i++) printf("%i, ", tracker[i]);
printf("\n");

int l = 0;
for(int i = 0; i < numOfCommands; i++) {
    int status;
    if((tracker[i] == 1) && (strcmp(args[l], "exit") == 0)) {
        printf("Reached an exit2\n");
        exitProgram = 1;
        continue;
    }
    char *holder[tracker[i]+1];
    for(int j = 0; j < tracker[i]; j++) {
        holder[j] = args[l];
        l++;
    }
    holder[tracker[i]] = NULL;
    for(int o = 0; o < tracker[i]; o++) {
        printf("Holder is: %s\n", holder[o]);
    }
    pid_t p = fork();
    pid_t waiting;
    if(p == 0) {
    printf("I am in child process\n");
    execvp(holder[0], holder);

    fprintf(stderr, "Child process could not execvp!\n");
    exit(1);
    }
    else {
        if(p < 0) {
            fprintf(stderr, "Fork FAILED!\n");
        }
        else {
            waiting = wait(&status);
            printf("Child %d, status %d\n", waiting, status);
        }
    }
    for(int i = 0; i < numOfCommands; i++) {
        args[i] = NULL;
    }
}

}   

return 0;

}

1 个答案:

答案 0 :(得分:0)

我想出了答案。我有一个嵌套的for循环使用相同的迭代变量名称,这导致我的迭代跳转到不需要的位置。