我正在创建自己的 shell,在这个函数中传递带有 2 个参数的命令时遇到问题:
void executeCMD(char **av)
{
int status;
pid_t pid;
pid = fork();
if (pid == -1)
{
perror("error");
exit(1);
}
if (pid == 0)
{
if (execve(av[0], av, NULL) == -1)
{
perror("Error");
exit(1);
}
}
else
{
wait(&status);
}
}
如果我通过了类似的东西: /bin/ls 或者 /bin/ls -l 它工作正常,但使用类似的东西:
/bin/ls -l /tmp
我明白了:
$ ls -l /tmp
Error: Bad address
问题出在所有命令中,特别是当我添加第三个参数时。
我如何创建命令,将缓冲区作为命令和参数传递给 **av:
char **split_string(char *input, char *delim)
{
char **list = NULL;
int i = 0;
char* token = strtok(input, delim);
while (token != NULL)
{
list = realloc(list, (i + 1) * sizeof(char *));
if (list == NULL)
{
perror("out of memory");
exit(1);
}
list[i] = realloc(list[i], strlen(token) + 1);
if (list[i] == NULL)
{
perror("out of memory");
exit(1);
}
strcpy(list[i], strdup(token));
token = strtok(NULL, delim);
i++;
}
return (list);
}
我认为您也将路径 av[0] 提供给了 argv。也许尝试: execve(av[0], av+1, NULL).
并确保 av 以 null 终止。而且我认为你也只能传递 2 个参数,因此给出 -i 和 /tmp 可能是 null 终止之前的最大值。