2

我知道在linux中使用命令“chroot”需要一些文件或目录,例如usrbin等等。但是当我chroot()在 C 中使用该函数时,我需要这些文件吗?

这是我的代码,其中“hw.out”是一个二进制文件,只打印“Hello, world”。我编译它并以root身份运行它,但它无法打印“Hello,world”。我还应该做什么?谢谢!

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int result = chroot(".");

    if(result == 0)
        printf("Chroot Succese.\n");

    char *arrays[]={"./hw.out",NULL};
    execvp("./hw.out", arrays);
    return 0;
}
4

3 回答 3

4

execvp最有可能失败,可能与ENOENT: no such file or directory, ifhw.out是一个动态链接的可执行文件。

为此,hw.out需要在chrooted 环境中找到所需的所有库。

尝试hw.out静态链接,它应该可以工作。(并在调用后添加错误检查execvp以查看errno调用后的设置(如果它返回)。)

于 2012-03-15T08:05:33.737 回答
1

请测试您是否hw.out使用命令行 chroot。

也许 hw.out 是动态链接的,并且缺少一些库或ld-linux.so在 chroot 目录中。

Nitpicks 1,return 0execvp之后有什么意义?除非出现错误,否则它永远不会被执行。我宁愿有perror("can't exec"); return 1;

Nitpick 2,chroot() 不会更改工作目录,尽管它适用于您的情况,因为您正在 chrooting 到".",但如果您稍后将其更改为 chroot("somedir"),它将无法按预期工作。

于 2012-03-15T08:07:51.310 回答
0

确保hw.out是正确的直接。如果它使用库,可能更容易将其静态链接。否则需要在 chroot 之后启用它才能访问动态库。

于 2012-03-15T08:10:52.320 回答