Chdir lagging Shell



我正在用C/c++编写一个shell。当我尝试使用chdir(const char*)更改目录时,shell开始延迟。shell工作得非常好,直到输入cd ..之类的东西。然后,当我尝试输入ls时,它说它不能执行couldn't execute: l(而不是ls)。to build:g++ main.cc -lreadline

#include <stdio.h>
#include <readline/readline.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string>
#define clear printf("33[H33[J")
char** getInput(char* input)
{
char** command = (char**) malloc(8 * sizeof(char*));
char* separator = " ";
char* parsed;
int index = 0;
parsed = strtok(input, separator);
while (parsed != NULL)
{
command[index] = parsed;
index++;
parsed = strtok(NULL, separator);
}
command[index] = NULL;
return command;
}
int main()
{
char** command;
char* input;
pid_t child_pid;
int stat_loc;
bool loop = true;
do
{
input = readline("");
command = getInput(input);
child_pid = fork();
if (child_pid < 0)
{
printf("Fork Failedn");
exit(0);
}
if (strncmp(command[0], "cdn", 2) == 0)
{
if (chdir(std::string(command[1]).c_str()) < 0)
printf("Couldn't execute: %sn", command[1]);
continue;
}
else if (child_pid == 0)
{
execvp(command[0], command);
printf("couldn't execute: %sn", input);
}
else waitpid(child_pid, &stat_loc, WUNTRACED);
free(input);
free(command);
} while (loop);
}

您在错误的位置分叉,导致在使用命令cd时产生多个子节点。除此之外,cd命令的continue阻止释放inputcommand。此外,子进程需要在运行命令后打破循环退出。

:

child_pid = fork();
if (child_pid < 0)
{
printf("Fork Failedn");
exit(0);
}
if (strncmp(command[0], "cdn", 2) == 0)
{
if (chdir(std::string(command[1]).c_str()) < 0)
printf("Couldn't execute: %sn", command[1]);
continue;
}
else if (child_pid == 0)
{
execvp(command[0], command);
printf("couldn't execute: %sn", input);
}
else waitpid(child_pid, &stat_loc, WUNTRACED);

应:

if (strncmp(command[0], "cdn", 2) == 0)
{
if (chdir(std::string(command[1]).c_str()) < 0)
printf("Couldn't execute: %sn", command[1]);
free(input);
free(command);
continue;
}
child_pid = fork();
if (child_pid < 0)
{
printf("Fork Failedn");
exit(0);
}
else if (child_pid == 0)
{
execvp(command[0], command);
printf("couldn't execute: %sn", input);
loop = false;
// or:
//free(input);
//free(command);
//exit(0);
}
else waitpid(child_pid, &stat_loc, WUNTRACED);

相关内容

  • 没有找到相关文章

最新更新