How does a running application on Linux / * nix determine its own absolute path?
Let's assume that you start the application "application" by typing "application" and not its absolute path. Because of the $ PATH variable, / foo / bar / app actually works. From within the application, I would like to define / foo / bar / app. argv [0] is just an "application", so it doesn't help.
I know in Linux, I can look at
/ Proc / i / ex
but that doesn't work on other * nix, in particular OS X. Is there a more portable way to define the directory in which the application is running?
a source to share
I ended up mimicking the "which" program and looking at each directory in $ PATH to see if the executable is $ dir / app:
if (strchr(progname, '/') == NULL) {
std::string pathStr = getenv("PATH");
std::string testDir;
pathStr += ":"; // add a trailing ':' to make search easier
size_t pos = 0;
bool found = false;
while (!found && ((pos = pathStr.find(":")) != std::string::npos)) {
testDir = pathStr.substr(0, pos);
testPath = testDir + "/" + progname;
pathStr = pathStr.substr(pos + 1, pathStr.size() - pos + 1);
if (access(testPath.c_str(), X_OK) == 0)
found = true;
}
if (found)
dir = testDir.c_str();
}
a source to share
Don't use path, use / proc. This is what code I wrote
const char* eif_ft__binary_file()
{
#ifdef OS_WINDOWS
wchar_t* p = (wchar_t*)malloc(282 * sizeof(wchar_t));
GetModuleFileNameW(NULL, p, 280);
char* res = transform__utf16_to_utf8(p,-1,NULL);
free(p);
return res;
#elif OS_LINUX
char* path = (char*)malloc(512);
int res = readlink("/proc/self/exe", path, 510);
if (res == -1) { free(path); return ""; }
path[res]=0;
TEMP_STRING_1 = path;
free(path);
return TEMP_STRING_1.text();
#elif OS_SOLARIS
char* path = (char*)malloc(512);
int res = readlink("/proc/self/path/a.out", path, 510);
if (res == -1) { free(path); return ""; }
path[res]=0;
TEMP_STRING_1 = path;
free(path);
return TEMP_STRING_1.text();
#elif OS_FREEBSD
char* path = (char*)malloc(512);
int res = readlink("/proc/curproc/file", path, 510);
if (res == -1) { free(path); return ""; }
path[res]=0;
TEMP_STRING_1 = path;
free(path);
return TEMP_STRING_1.text();
#else
TEMP_STRING_1 = "";
return TEMP_STRING_1.text();
#endif
}
TEMP_STRING ist just a generic macro for the String class.
a source to share
I'm not sure if there is a good portable way to do this.
On OS X you can use _NSGetExecutablePath()
(then apply realpath()
to result if you like).
a source to share