所以我试图在c中创建一个shell脚本。它必须执行以下操作: *退出用户输入;放弃 *处理最多一个参数的命令
作为内部流程和流程控制的初学者,我遇到了麻烦,可以在正确的方向上使用一个点。出于某种原因,无论输入什么,它都只能打印出来。这就是我现在所拥有的,我错过了什么?或者我做错了什么?
int main(){
int total_args;
char *arg[3];
pid_t cpid;
char shell_prompt[] = "console:";
char line[MAX_LINE];
char command[MAX_LINE];
char argument[MAX_LINE];
while(!0){
printf("%s", shell_prompt);
fgets(line, MAX_LINE, stdin);
total_args = sscanf(line, "%s %s", command, command_argument);
arg[0] = (char *) malloc(strlen(command));
.....
}
答案 0 :(得分:1)
为要复制的字符串分配存储空间时,需要为'\0'
终结符添加其他字符,因此:
arg[1] = (char *) malloc(strlen(command_argument));
需要:
arg[1] = malloc(strlen(command_argument) + 1);
否则后续对strcpy
的调用将超出分配存储的范围。
另请注意,我已删除了redundant and potentially dangerous cast on the result of of malloc。