[英]Why isn't my C shell outputting anything?
处理 class 的项目。 我们应该写一个 C shell。 我找到了一堆很好的例子,但对于我的生活,我无法让我的版本生成任何 output。
它不断打印提示,但没有别的。
我已经跟随一些例子几乎逐字地试图解决这个问题,但仍然没有。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <sys/wait.h>
/******************************************
@brief Fork a child to execute the command using execvp. The parent should wait for the child to terminate
@param args Null terminated list of arguments (including program).
@return returns 1, to continue execution and 0 to terminate the MyShell prompt.
******************************************/
int execute(char **args)
{
pid_t pid;
int status;
if ((pid = fork()) < 0)
{
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0)
{
if (execvp(*args, args) < 0) {
printf("*** ERROR: exec failed\n");
exit(1);
}
}
else
{
while (wait(&status) != pid)
;
}
return 0;
}
/******************************************
@brief gets the input from the prompt and splits it into tokens. Prepares the arguments for execvp
@return returns char** args to be used by execvp
******************************************/
char** parse(void)
{
//Get the string and store it. Remove newline.
char strIn[255];
printf("MyShell>");
fgets(strIn, sizeof(strIn), stdin);
strIn[strlen(strIn)-1]='\0';
//Array, token, counters.
char *args[20];
char *tok;
int i = 0;
int count = 0;
//Allocate array.
for(i = 0; i < 20; i++)
{
args[i] = (char*)malloc(20 * sizeof(char));
}
//Fill in args[0]
tok = strtok(strIn, " ");
strcpy(args[count++], tok);
//Fill in array with tokens.
while (tok != NULL)
{
tok = strtok(NULL, " ");
if (tok == NULL)
break;
strcpy(args[count++], tok);
}
//Null terminate.
args[count] = NULL;
return args;
}
/******************************************
@brief Main function should run infinitely until terminated manually using CTRL+C or typing in the exit command
It should call the parse() and execute() functions
@param argc Argument count.
@param argv Argument vector.
@return status code
******************************************/
int main(int argc, char **argv)
{
bool run = true;
while(run)
{
char** argArr = parse();
execute(argArr);
}
return 0;
}
output,不管我做什么,都是:
MyShell>
MyShell>
MyShell>
有人能告诉我哪里出错了吗?
parse()
返回一个指向本地数组args
的指针。 由于args
的生命周期在parse()
返回时结束,因此任何使用parse()
的返回值的尝试都是未定义的行为。 您应该使用malloc()
分配该数组(并稍后释放它。)。
在我的测试中发生的是编译器注意到parse()
的返回值不能合法使用(它会发出警告!!你应该阅读并注意!! ),所以它只返回NULL
. 当孩子将此指针取消引用为*args
以获取execvp
的第一个参数时,它会出现段错误并在不调用execvp()
的情况下死亡。 如果您检查wait()
返回的status
,您可以检测到这一点,但您没有。 所以看起来孩子什么也没做。
哦,额外的错误:当stdin
上出现文件结束时(例如,如果您按 Ctrl-D), fgets()
返回的字符串将为空并且strIn[strlen(strIn)-1]='\0';
将存储超出范围的 null 字节。 您需要测试fgets()
的返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.