为什么我的代码在没有 chroot 函数的情况下工作,但使用 chroot 函数失败?

Why my code works without chroot function, but fail with chroot function?

本文关键字:chroot 函数 失败 工作 代码 我的 为什么 情况下      更新时间:2023-10-16

我试图让我的代码在chroot('/root/test1')下工作,但它不能正常工作。

但是当我删除chroot('/root/test1'),并将execl("/test2", "test2", NULL)修改为execl("/root/test1/test2", "test2", NULL)时,它会按预期很好地工作。为什么?

另外,我想问一下,如果我fp重定向到stdin,然后使用execl函数工作另一个程序,子程序将获得输入fp是否?

'/root/test1/' 中的文件:

test2
test2.cpp
test3
test3.cpp

execl 函数返回的值为 -1,errno 为 2。

测试3.cpp

int main() {
FILE *fp;
errno = 0;
fp = fopen("log.txt", "r");
dup2(fileno(fp), fileno(stdin));
cout << chdir("/root/test1") << endl;
cout << chroot("/root/test1") << endl;
DIR *dir = opendir("/");
dirent *list;
while ((list = readdir(dir)) != NULL) {
cout << list -> d_name << "  ";
}
cout << endl;
closedir(dir);
errno = 0;
cout << execl("/test2", "test2", NULL) << endl;
cout << errno << endl;
cout << strerror(errno) << endl;
return 0;
}

测试2.cpp

#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int a,b;
cin >> a;
scanf("%d",&b);
cout << a+b << endl;
printf("%d",a+b);
return 0;
}

日志.txt

111 222

输出*

0
0
.  test3.cpp  test3  ..  test2  test2.cpp  log.txt
-1
2
No such file or directory

将/usr/lib/lib64 和/bin/bash 复制到/root/test1