Friday, December 7, 2007

Getting current executable path name on Linux

After much browsing which yielded negative results (as in - there is no portable way of doing it), I started browsing through the process filesystem (/proc).

Almost immediately I hit on /proc/self which is a link pointing to the current process pid directory. From there, doing the ls -l /proc/self/* I noticed that exe was pointing to /bin/ls. Well, it does not take a rocket scientist...

So the solution is:

char procname[FILENAME_MAX];
int len = readlink("/proc/self/exe", procname, FILENAME_MAX - 1);
if (len <= 0) {
// I guess we're not running on the right version of unix
return FALSE;
procname[len] = '\0';

Why does not argv[0] work? Because it's what user literally typed in, argv[0] for a ls command would be just that - "ls". The recommendations on the web were basically to check if argv[0] starts with '/'. If yes, maybe it's the process (although not guaranteed because it can be exec'd with any argv[0] at all, not necessary the process name). If it's not '/', then if it starts with "./" use getcwd, otherwise enumerate the path...

I'll take the /proc/self/exe approach thank you very much!

No comments: