【问题标题】:My chdir() function will not work. Why?我的 chdir() 函数将不起作用。为什么?
【发布时间】:2014-01-31 05:40:05
【问题描述】:

我正在编写一个程序,它要求用户输入一个 linux bash 命令,然后将它们存储在指针数组中(有点像 char *argv[])。然后程序必须检查该命令是普通的 bash 命令还是cd (change directory) 命令。如果它是一个cd 命令,那么它应该使用类似chdir() 的东西。如果该命令是其他命令,我想使用exec() 系统调用的一些变体来执行该命令。

但是我在第一部分没有成功 (chdir())。

int ii=-1
printf("Enter the command: ");
fgets(command, 100, stdin);
command[strlen(command)-1]=0;
printf("Command = %s\n", command);


if (command[0]=='c' && command[1]=='d' && command[2]==' ')
{
    printf("I am inside CD now.\n");
    cd_dump[0] = strtok(command," ");
    while(sub_string[++ii]=strtok(NULL, " ") != NULL)
    {
        printf("%s\n", sub_string[0]);
    }

    chdir(sub_string[0]);
}

编辑: 我也尝试了以下 if 语句,但没有运气。

if (command[0]=='c' && command[1]=='d' && command[2]==' ')
{
    printf("I am inside CD now.\n");
    chdir(command+3);
}

遗憾的是,该程序并没有按照我的意愿行事,即使在尝试解决问题数小时后,我也不知道为什么。我做错了什么?另外,如果我输入cd /home/,为什么 sub_string[0] 中的输出结果会在输出中出现额外的“Enter 键”? strtok 是否将 Enter 键保存到字符串中?

非常感谢您对此主题的任何帮助。

【问题讨论】:

标签: c linux bash strtok chdir


【解决方案1】:

调用chdir()只影响当前进程,不影响其父进程。

如果你 chdir() 并立即退出,那是没有意义的——你调用它的 shell 会保留它的旧 cwd。这就是为什么 cd 始终是一个内置的 shell。

使用

char buffer[PATH_MAX];
if (getcwd(buffer, sizeof buffer) >= 0) {
    printf("Old wd: %s\n", buffer);
}
chdir(command+3);
if (getcwd(buffer, sizeof buffer) >= 0) {
    printf("New wd: %s\n", buffer);
}

验证chdir() 工作正常。

【讨论】:

    【解决方案2】:

    我想我会这样做:

    if (command[0]=='c' && command[1]=='d' && command[2]==' ')
    {
        for(i=2, i++, command[i]!=' ');  /* Skip to nonspace */
        chdir(command+i);
    }
    

    【讨论】:

    • chdir(command+3) 不是完全一样的吗?我也不太明白这个循环。当i=3 在循环中chdir() 命令将指向command+3,之后会发生什么?循环什么时候退出?
    • 那个 for 循环不正确。它缺少任何;,如果i++ 应该是测试,它将是true,可能会进行多次迭代。
    • 考虑 chdir(command+3) 在以下情况下会做什么:command="cd\x20\x20\x20\x20\x20fred"
    猜你喜欢
    • 1970-01-01
    • 2021-03-21
    • 2021-12-18
    • 2011-06-23
    • 1970-01-01
    • 2017-08-18
    • 2010-10-18
    • 1970-01-01
    • 2022-11-25
    相关资源
    最近更新 更多