ExecCurrentPath ExecCurrentPath char buff PATH_MAX ssize_t len readlin

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
ExecCurrentPath::ExecCurrentPath() {
char buff[PATH_MAX];
ssize_t len = readlink("/proc/self/exe", buff, sizeof(buff)-1);
if (len != -1) {
buff[len] = '\0';
execpath = core::filesystem::canonical(core::filesystem::absolute(buff));
if (execpath.filename() == ld_str) { // мы запущены из под ld-linux-x86-64.so.2
std::ifstream fin("/proc/self/cmdline");
std::string str;
while (std::getline(fin, str, '\0'))
{
std::cout << str << std::endl;
if (str.length() >= ld_str.length() && str.compare(str.length() - ld_str.length(), ld_str.length(), ld_str) == 0) {
continue;
}
if (str == "--library-path" || str == "--inhibit-rpath") {
if (std::getline(fin, str, '\0')) {
continue;
} else {
throw std::logic_error("we were expecting that we run from ld-linux-x86-64.so.2 but something went wrong");
}
} else {
// наш ld всегда имеет полный путь к файлу
execpath = str;
path = execpath.parent_path();
return;
}
}
throw std::logic_error("we were expecting that we run from ld-linux-x86-64.so.2 but something went wrong 2");
}
path = execpath.parent_path();
} else {
throw std::logic_error("Unable to use readlink");
}
}