【问题标题】:Strange bug with chdir in cc中chdir的奇怪错误
【发布时间】:2015-11-15 16:06:02
【问题描述】:

构建一个像 prog 这样的小 shell

我尝试制作 cd 命令,所以我使用:

if (!strcmp(cmd, "cd") ) 
    {
        if(chdir("args[1]")!=0){
            printf(" %s - path not found\n",args[1]);
            perror("Error:");
        }
    } 

输出是这样的:

smash > cd /home/johnny/workspace/
 /home/johnny/workspace/ - path not found
Error:: No such file or directory
smash > cd test
 test - path not found
Error:: No such file or directory

ps 在工作目录中有一个“test”文件夹

pps 也许你们可以帮助我如何制作“cd ..”命令

【问题讨论】:

  • chdir("args[1]") - 你确定你有一个名为args[1] 的目录吗?因为在 C 中字符串文字不会被解析以考虑变量等,所以这不是 PHP。你想要做的是(可能)chdir(args[1])(注意没有双引号)。
  • 研究现有shell的源代码以获得灵感
  • 一般来说,对perror()的调用需要在调用设置errno的系统函数之后立即进行。在将参数更正为chdir() 之后,发布的代码包含对printf() 的干预调用,如果出错,它会更改errno 中的值。建议在拨打chdir()之后立即拨打perror()

标签: c linux unix chdir


【解决方案1】:

您将实际字符串"args[1]" 传递给chdir。这可能不是你想要的,而是你想要的 chdir(args[1]) 所以你的代码看起来像这样:

if (!strcmp(cmd, "cd") ) 
    {
        if(chdir(args[1])!=0){
            fprintf(stderr, "chdir %s failed: %s\n", args[1], strerror(errno));
        }
    } 

printf 的输出来看,您的路径似乎没问题,请注意在printf 中您没有"args[1]",而是有args[1]

正如@BasileStarynkevitch 在下面的评论中指出的那样:

perrorprintf 错误之后(因为失败的printf 会 更改errno)。

因此你应该使用上面的fprintf

【讨论】:

  • perrorprintf 错误之后(因为失败的printf 会更改errno)。将 printfperror 调用替换为:fprintf(stderr, "chdir %s failed: %s\n", args[1], strerror(errno));
猜你喜欢
  • 2014-05-08
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
相关资源
最近更新 更多