// Executable Name // // Douglas Thrift // // $Id$ #include #include #include #include extern "C" { #include #include #include #include } #include int main(int argc, char* argv[]) { std::string program(argv[0]); if (program.find('/') == std::string::npos) { std::istringstream path(::getenv("PATH") != NULL ? ::getenv("PATH") : std::string()); do { std::string candidate; std::getline(path, candidate, ':'); candidate += '/' + program; if (::access(candidate.c_str(), X_OK) == 0) { struct ::stat file; if (::stat(candidate.c_str(), &file) == 0 && S_ISREG(file.st_mode) && (::getuid() != 0 || (file.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0)) { ::lstat(candidate.c_str(), &file); if (S_ISLNK(file.st_mode)) { char buffer[1024]; int length(::readlink(candidate.c_str(), buffer, 1024)); if (length == -1) { ::perror(argv[0]); return 1; } program.assign(buffer, length); } else program = candidate; break; } } } while (path.good()); } char executable[PATH_MAX]; if (::realpath(program.c_str(), executable) == NULL) { ::perror(argv[0]); return 1; } std::cout << "executable = " << executable << '\n'; return 0; }