gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:43:17 25 4
gpt4 key购买 nike

我正在编写创建一个小 shell 的代码。我在尝试让我的代码读取多个命令时遇到问题。每个命令由“;”分隔特点。例如,如果我运行我的代码并键入“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;

}

最佳答案

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

关于c - 读取多个命令传递给 execvp(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39549221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com