Skip to content

Instantly share code, notes, and snippets.

@phlash
Created September 12, 2021 21:52
Show Gist options
  • Save phlash/b4263dab4f381fa02b6dc2247817f38e to your computer and use it in GitHub Desktop.
Save phlash/b4263dab4f381fa02b6dc2247817f38e to your computer and use it in GitHub Desktop.
Linux - finding the executable path reliably (no /proc, invalid argv[0] from caller)
// run supplied program but with argv[0] replaced by 'FAKEME'
#include <unistd.h>
int main(int argc, char **argv) {
char *file = argv[1];
argv[1] = "FAKEME!";
execvp(file, &argv[1]);
}
// experiments in locating one's own executable path
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/auxv.h>
int main(int argc, char **argv) {
// grab the AUXV_EXECFN path
char *cwd = getcwd(NULL, 0);
char *path = (char *)getauxval(AT_EXECFN);
if (!cwd) {
puts("getcwd() returns NULL?");
return 1;
}
if (!path) {
puts("AT_EXECFN not available?");
return 2;
}
char *me = path;
// resolve non-absolute path's via cwd
if (path[0]!='/') {
char *srch = malloc(strlen(cwd)+strlen(path)+2);
strcpy(srch, cwd);
strcat(srch, "/");
strcat(srch, path);
me = realpath(srch, NULL);
}
printf("cwd=%s, argv[0]=%s, AT_EXECFN=%s me=%s\n", cwd, argv[0], path, me);
return 0;
}
# Build/test findme program
all: tests
clean:
@rm -rf fakeme findme
tests: bins
@echo '--- Run directly from the shell, relative location ---'
./findme
@echo '--- Run directly from the shell, absolute location ---'
$$PWD/findme
@echo '--- Run with a fake argv[0], relative location ---'
./fakeme ./findme
@echo '--- Run with a fake argv[0], absolute location ---'
./fakeme $$PWD/findme
@echo '--- Run via the PATH, no location ---'
PATH=$$PATH:$$PWD findme
@echo '--- Run via the PATH, fake argv[0] ---'
PATH=$$PATH:$$PWD fakeme findme
bins: fakeme findme
%: %.c
gcc -o $@ $<
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment