10 * This function returns the absolute path to the executable it is running in.
12 * The implementation follows http://stackoverflow.com/a/933996/712014
15 const char *get_exe_path(const char *argv0) {
16 static char destpath[PATH_MAX];
19 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
20 /* Linux and Debian/kFreeBSD provide /proc/self/exe */
21 #if defined(__linux__) || defined(__FreeBSD_kernel__)
22 const char *exepath = "/proc/self/exe";
23 #elif defined(__FreeBSD__)
24 const char *exepath = "/proc/curproc/file";
28 if ((linksize = readlink(exepath, destpath, sizeof(destpath) - 1)) != -1) {
29 /* readlink() does not NULL-terminate strings, so we have to. */
30 destpath[linksize] = '\0';
36 /* argv[0] is most likely a full path if it starts with a slash. */
40 /* if argv[0] contains a /, prepend the working directory */
41 if (strchr(argv0, '/') != NULL &&
42 getcwd(tmp, sizeof(tmp)) != NULL) {
43 snprintf(destpath, sizeof(destpath), "%s/%s", tmp, argv0);
47 /* Fall back to searching $PATH (or _CS_PATH in absence of $PATH). */
48 char *path = getenv("PATH");
50 /* _CS_PATH is typically something like "/bin:/usr/bin" */
51 confstr(_CS_PATH, tmp, sizeof(tmp));
52 sasprintf(&path, ":%s", tmp);
56 const char *component;
59 if ((component = strtok(str, ":")) == NULL)
62 snprintf(destpath, sizeof(destpath), "%s/%s", component, argv0);
63 /* Of course this is not 100% equivalent to actually exec()ing the
65 if (access(destpath, X_OK) == 0) {
72 /* Last resort: maybe it’s in /usr/bin? */
73 return "/usr/bin/i3-nagbar";