我正在用 C/C 撰寫一個 shell。當我嘗試使用 更改目錄時chdir(const char*),shell 開始滯后。在cd ..輸入類似的東西之前,shell 作業得很好。然后當我嘗試輸入時ls,它說它無法執行couldn't execute: l(不是ls)。建立: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("\033[H\033[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 Failed\n");
exit(0);
}
if (strncmp(command[0], "cd\n", 2) == 0)
{
if (chdir(std::string(command[1]).c_str()) < 0)
printf("Couldn't execute: %s\n", command[1]);
continue;
}
else if (child_pid == 0)
{
execvp(command[0], command);
printf("couldn't execute: %s\n", input);
}
else waitpid(child_pid, &stat_loc, WUNTRACED);
free(input);
free(command);
} while (loop);
}
uj5u.com熱心網友回復:
您在錯誤的位置分叉,導致在使用 command 時產生多個子項cd。除此之外,continuefor 命令會cd阻止釋放input和command. 此外,孩子需要在運行命令后中斷回圈才能退出。
所以這:
child_pid = fork();
if (child_pid < 0)
{
printf("Fork Failed\n");
exit(0);
}
if (strncmp(command[0], "cd\n", 2) == 0)
{
if (chdir(std::string(command[1]).c_str()) < 0)
printf("Couldn't execute: %s\n", command[1]);
continue;
}
else if (child_pid == 0)
{
execvp(command[0], command);
printf("couldn't execute: %s\n", input);
}
else waitpid(child_pid, &stat_loc, WUNTRACED);
應該:
if (strncmp(command[0], "cd\n", 2) == 0)
{
if (chdir(std::string(command[1]).c_str()) < 0)
printf("Couldn't execute: %s\n", command[1]);
free(input);
free(command);
continue;
}
child_pid = fork();
if (child_pid < 0)
{
printf("Fork Failed\n");
exit(0);
}
else if (child_pid == 0)
{
execvp(command[0], command);
printf("couldn't execute: %s\n", input);
loop = false;
// or:
//free(input);
//free(command);
//exit(0);
}
else waitpid(child_pid, &stat_loc, WUNTRACED);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/324289.html
