gpt4 book ai didi

c - 如何在 c 中成功创建一个 shell,当它后面跟着一个包含命令的文本文件时,它会解析该文件并执行命令?

转载 作者:行者123 更新时间:2023-11-30 17:38:56 25 4
gpt4 key购买 nike

我的 shell 有两种模式:交互模式和文件模式。交互模式工作正常并且包含基本的 shell 操作。文件模式是我很难弄清楚的部分。要启动文件模式,您必须输入 shell 的名称,并在其后面直接输入一个包含命令的文本文件,例如) ./myShellCommands.txt当我运行它时,它打印出文本文件中的命令,但它不执行命令,并且显示“ls::没有这样的文件或目录”。我想知道是否有人可以帮助我找出我做错了什么。谢谢你!我正在测试的文本文件包含以下格式的两个命令:ls-l

  #include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
void parse(char *input, char **vparas)
{

while(*input != '\0')
{
while(*input == ' ' || *input == '\t' || *input == '\n')
*input++ = '\0';
*vparas++ = input;
while(*input != '\0' && *input != ' ' && *input != '\t' && *input != '\n')
{
input++;
}
}
*vparas = '\0';
}
int main(int argc, char *argv[])
{
int x;
//file stuff///////////////////////////////////////////////////
if(argc!= 2)
printf("");
else
{
FILE *file = fopen(argv[1], "r");
if(file == 0)
{
printf("Could not open file\n");
}
else
{
//get string and set it equal to some array

char fileInput[1024];

fgets(fileInput, 1024, file);
printf("%s", fileInput);
char *vparas[20];
parse(fileInput, vparas);

//execute file commands
pid_t pid1;
pid1 = fork();
if(pid1<0)
{
printf("Fork Failed");
return 1;
}
else if(pid1 == 0)
execvp(*vparas,vparas);
else
wait(NULL);
fclose(file);
}
}
///////////////////////////////////////////////
char input[1024];
char *args[64];
while(1)
{
printf("@");
gets(input);

printf("\n");

//parse the line
parse(input, args);
if(strcmp(args[0], "exit") == 0)
return 0;
//execute command

pid_t pid;
pid = fork();
if(pid<0)
{
printf("Fork Failed");
return 1;
}
else if(pid== 0)
{
execvp(*args, args);

}
else
{
wait(NULL);
}
}
return 0;
}

最佳答案

由于您使用 fgets() 从文件中读取,因此读取的字符串将包含最后一个额外字符(主要是换行符)。因此,您需要将其更改为“\0”字符,然后从文件输入的命令的执行将被正确解析。在 fgets() 之后添加此行。

fileInput[strlen(fileInput)-1]='\0';

它将执行文件中的单个命令。对于多个命令,您可以从循环内的文件中读取。

while(fgets(fileInput, 1024, file))
{
//rest of the code
}

关于c - 如何在 c 中成功创建一个 shell,当它后面跟着一个包含命令的文本文件时,它会解析该文件并执行命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22000214/

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