c语言 - rm 成功,但它打印出来 rm:无法删除:没有这样的文件或目录



我正在linux中构建一个小shell。运行ls -la /tmp > output之后,我可以使用cat查看输出。如果我尝试rm输出,则删除成功,但显示rm: cannot remove '': No such file or directory.

这是我的代码

int main(int argc, char *argv[]) {
char line[LINESZ + 2];
cmd_string C;
initialize(&C);
while (1) {
// Free up allocated memory, if any
FREE_ALLOCATED_MEMORY(C);
// Let's print the shell prompt
printf("tinyshell> ");
// read a line (i.e., input string) from stdin
if (fgets(line, LINESZ, stdin) == NULL) {
return 0; // reached EOF (end-of-file), so we can safely terminate
}
parse_cmd_string(line, &C);
unsigned char r = process_builtin_commands(&C);
if (r == 1)
continue; 
int fc = fork();
if (fc < 0) {
PRINT_ERROR_SYSCALL("fork");
return 1;
} else
if (fc == 0) {
char *myargs[strlen(*C.args) + 1];
for (int i = 0; i < strlen(*C.args); i++) {
myargs[i] = C.args[i];
}
myargs[strlen(*C.args) + 1] = NULL;
if (execvp(myargs[0], myargs) < 0) {
PRINT_ERROR_SYSCALL("execvp");
}
FREE_ALLOCATED_MEMORY(C);
return 1;
}
}
}

代码不一致:

  • 数组myargs中的元素数量是1加上第一个参数字符串的长度,可能是命令的名称。这似乎不正确
  • 从数组CCD_ 7分配CCD_ 6字符串指针。同样,如果用较少的元素定义此数组,则这似乎是不正确的,并且可能具有未定义的行为
  • 您试图用myargs[strlen(*C.args)+1] = NULL;在数组末尾设置一个NULL指针终止符,但实际上您在数组末尾之后设置了元素,这具有未定义的行为

以这种方式运行具有潜在随机参数的rm命令是在玩火。幸运的是,在这个奇怪的诊断消息之前,没有删除任何有用的文件,这可能是由数组末尾的空字符串参数引起的。

正如Keith Thomson所评论的那样,如果您想测试一个可能无法正常工作的shell,请使用类似echo的东西,而不是rm

最新更新