Instead of using readlink to discover the path to your own executable, you can directly call open on /proc/self/exe. Since the kernel already has an open fd to processes that are currently executing, this will give you an fd regardless of whether the path has been replaced with a new executable or not.

Next, you can use fexecve instead of execv which accepts an fd parameter instead of a filename parameter for the executable.

int fd = open("/proc/self/exe", O_RDONLY);
fexecve(fd, argv, envp);

Above code omits error handling for brevity.

Answer from andrewrk on Stack Overflow
Top answer
1 of 3
9

Instead of using readlink to discover the path to your own executable, you can directly call open on /proc/self/exe. Since the kernel already has an open fd to processes that are currently executing, this will give you an fd regardless of whether the path has been replaced with a new executable or not.

Next, you can use fexecve instead of execv which accepts an fd parameter instead of a filename parameter for the executable.

int fd = open("/proc/self/exe", O_RDONLY);
fexecve(fd, argv, envp);

Above code omits error handling for brevity.

2 of 3
3

One solution is at executable startup (e.g. near the beginning of main()) to read the value of the link /proc/self/exe once and store it statically for future use:

  static string savedBinary;
  static bool initialized = false;

  // To deal with issue of long running executable having its binary replaced
  // with a newer one on disk, we compute the resolved binary once at startup.
  if (!initialized) {
    const size_t bufSize = PATH_MAX + 1;
    char dirNameBuffer[bufSize];
    // Read the symbolic link '/proc/self/exe'.
    const char *linkName = "/proc/self/exe";
    const int ret = int(readlink(linkName, dirNameBuffer, bufSize - 1));

    savedBinary = dirNameBuffer;

    // On at least Linux, if the executable is replaced, readlink() of
    // "/proc/self/exe" gives "/usr/local/bin/flume (deleted)".
    // Therefore, we just compute the binary location statically once at
    // startup, before it can possibly be replaced, but we leave this code
    // here as an extra precaution.
    const string deleted(" (deleted)");
    const size_t deletedSize = deleted.size();
    const size_t pathSize = savedBinary.size();

    if (pathSize > deletedSize) {
      const size_t matchPos = pathSize - deletedSize;

      if (0 == savedBinary.compare(matchPos, deletedSize, deleted)) {
        // Deleted original binary, Issue warning, throw an exception, or exit.
        // Or cludge the original path with: savedBinary.erase(matchPos);
      }
    }
    initialized = true;
  }

  // Use savedBinary value.

In this way, it is very unlikely that the original executable would be replaced within the microseconds of main() caching the path to its binary. Thus, a long running application (e.g. hours or days) could get replaced on disk, but per the original question, it could fork() and execv() to the updated binary that perhaps has a bug fix. This has the added benefit of working across platforms, and thus the differing Macintosh code to read the binary path could be likewise protected from binary replacement after startup.

WARNING editors note: readlink does not null terminate the string, so the above program may or may not work accidentally if the buffer was not filled with zeros before calling readlink

🌐
Reddit
reddit.com › r/cprogramming › readlink("/proc/self/exe" outputs two extra characters that are not part of the path of the runnable file.
r/cprogramming on Reddit: readlink("/proc/self/exe" outputs two extra characters that are not part of the path of the runnable file.
January 8, 2023 -

Getting the file path of an app runnable file with readlink("/proc/self/exe".... works alright. But if I rename the runnable file, stops working correctly:

The file path is mostly correct but for some reason readlink("/proc/self/exe" outputs two extra characters at the end of the file path. They are not part of the app runnable file path. This problem happens when a C program running in Linux calls readlink("/proc/self/exe" to get to know the path of its runnable file.

Do you know how to fix this?

Thanks

Discussions

linux - How does the /proc/<pid>/exe symlink differ from ordinary symlinks? - Unix & Linux Stack Exchange
The string that is returned as ... calls readlink on it. Under the hood, opening /proc//exe shortcuts the usual symbolic link resolution and directly opens the file description. The same applies to /proc//fd/, /proc//cwd, /proc//root and other similar links. Another example of a “magic” symbolic link is /proc/self... More on unix.stackexchange.com
🌐 unix.stackexchange.com
April 22, 2015
readlink /proc/self/exe permission denied inside created thread of container entry point
Docker Version: dnoor@gears:~/.../amps-docker/bug$ docker version Client: Version: 1.8.2 API version: 1.20 Go version: go1.4.2 Git commit: 0a8c2e3 Built: Thu Sep 10 19:08:45 UTC 2015 OS/Arch: linux... More on github.com
🌐 github.com
12
December 23, 2015
shell - Unable to use readlink for /proc/self/exe for a C program - Stack Overflow
The only output I get is readlink: No such file or directory when what I need is the name the executable ie, a.out. ... could you provide the code with ssize_t length = readlink("/proc/self/exe",target_path,sizeof (target_path));. have you tested with a hardcoded path ? More on stackoverflow.com
🌐 stackoverflow.com
September 27, 2016
`readlink /proc/self/exe` returns relative path if the executable begins with `./` under Parrot
Under Parrot, if we execute some commands accessing /proc/self/exe, such as parrot_run ./ls -l /proc/self/exe and the commands begins with ./, the result of the command will be relative path, the s... More on github.com
🌐 github.com
3
January 28, 2014
Top answer
1 of 5
44

This Use the readlink() function properly for the correct uses of the readlink function.

If you have your path in a std::string, you could do something like this:

#include <unistd.h>
#include <limits.h>

std::string do_readlink(std::string const& path) {
    char buff[PATH_MAX];
    ssize_t len = ::readlink(path.c_str(), buff, sizeof(buff)-1);
    if (len != -1) {
      buff[len] = '\0';
      return std::string(buff);
    }
    /* handle error condition */
}

If you're only after a fixed path:

std::string get_selfpath() {
    char buff[PATH_MAX];
    ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
    if (len != -1) {
      buff[len] = '\0';
      return std::string(buff);
    }
    /* handle error condition */
}

To use it:

int main()
{
  std::string selfpath = get_selfpath();
  std::cout << selfpath << std::endl;
  return 0;
}
2 of 5
6

Accepted answer is almost correct, except you can't rely on PATH_MAX because it is

not guaranteed to be defined per POSIX if the system does not have such limit.

(From readlink(2) manpage)

Also, when it's defined it doesn't always represent the "true" limit. (See http://insanecoding.blogspot.fr/2007/11/pathmax-simply-isnt.html )

The readlink's manpage also give a way to do that on symlink :

Using a statically sized buffer might not provide enough room for the symbolic link contents. The required size for the buffer can be obtained from the stat.st_size value returned by a call to lstat(2) on the link. However, the number of bytes written by readlink() and read‐ linkat() should be checked to make sure that the size of the symbolic link did not increase between the calls.

However in the case of /proc/self/exe/ as for most of /proc files, stat.st_size would be 0. The only remaining solution I see is to resize buffer while it doesn't fit.

I suggest the use of vector<char> as follow for this purpose:

std::string get_selfpath()
{
    std::vector<char> buf(400);
    ssize_t len;

    do
    {
        buf.resize(buf.size() + 100);
        len = ::readlink("/proc/self/exe", &(buf[0]), buf.size());
    } while (buf.size() == len);

    if (len > 0)
    {
        buf[len] = '\0';
        return (std::string(&(buf[0])));
    }
    /* handle error */
    return "";
}
🌐
IBM
ibm.com › support › pages › apar › IC43563
IC43563: CLEARCASE: 68 READLINK("/PROC/SELF/EXE",
When Java is imorted into a vob then run from the vob, some of the shared libraries cannot be found. JAVA is trying to find
🌐
Tibbsforge
tibbsforge.com › readlink-proc-self-exe
Understanding readlink /proc/self/exe and associated errors – tibbsforge
In the case of a C program, the readlink /proc/self/exe call returns the absolute path of the executable file. It is important to note that the value returned by readlink /proc/self/exe is limited by the size of the buffer used to store it.
🌐
GitHub
github.com › skuhl › sys-prog-examples › blob › master › simple-examples › readlink.c
sys-prog-examples/simple-examples/readlink.c at master · skuhl/sys-prog-examples
/* readlink() gives you the path that a symbolic link points · to. In this example, we get the path of the special link · /proc/self/exe which is always a symbolic link to the · executable on Linux machines.
Author   skuhl
Top answer
1 of 3
30

/proc/<pid>/exe does not follow the normal semantics for symbolic links. Technically this might count as a violation of POSIX, but /proc is a special filesystem after all.

/proc/<pid>/exe appears to be a symlink when you stat it. This is a convenient way for the kernel to export the pathname it knows for the process' executable. But when you actually open that "file", there is none of the normal procedure of reading the following the contents of a symlink. Instead the kernel just gives you access to the open file entry directly.

Notice that when you ls -l a /proc/<pid>/exe pseudofile for a process whose executable has been deleted the symlink target has the string " (deleted)" at the end of it. This would normally be non-sensical in a symlink: there definitely isn't a file that lives at the target path with a name that ends with " (deleted)".

tl;dr The proc filesystem implementation just does its own magic thing with pathname resolution.

2 of 3
5

According to the man page of /proc, under Linux 2.2 and later, the file is a symbolic link containing the actual pathname of the executed command. Apparently, the binary is loaded into memory, and /proc/[pid]/exe points to the content of the binary in memory.

On the other hand, under Linux 2.0 and earlier, /proc/[pid]/exe is apparently a pointer to the file (in the filesystem) which was executed.

So if you ran the same list of commands on Linux 2.0 or earlier, presumably you would get an error "no such file or directory".

🌐
GitHub
github.com › moby › moby › issues › 18883
readlink /proc/self/exe permission denied inside created thread of container entry point · Issue #18883 · moby/moby
December 23, 2015 - #include <pthread.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/syscall.h> int gettid() { return syscall(SYS_gettid); } void* check_proc_self_exe(void* unused) { const char *path = "/proc/self/exe"; char outputBuffer[256]; while(1) { memset(outputBuffer,0,sizeof(outputBuffer)); if(readlink(path,outputBuffer,sizeof(outputBuffer))==-1) fprintf(stderr,"pid %d tid %d path [%s] readlink error [%s]\n", getpid(),gettid(),path,strerror(errno)); else fprintf(stderr,"pid %d tid %d path [%s] readlink returned [%s]\n", getpid(),gettid(),path,outputBuffer); sleep(1); } return NULL; } int main() { pthread_t thread; pthread_create(&thread,NULL,check_proc_self_exe,NULL); /* never returns */ check_proc_self_exe(NULL); return 0; }
Author   moby
Find elsewhere
🌐
Red Hat
bugzilla.redhat.com › show_bug.cgi
1925786 – valgrind appears to only interject readlink on /proc/self/exe, not a direct open. this breaks programs
Red Hat Bugzilla – Bug 1925786 · This site requires JavaScript to be enabled to function correctly, please enable it · Privacy Contact FAQ Legal
🌐
Plan
saxonica.plan.io › issues › 2176
Support #2176: Unable to read link /proc/self/exe : Permission denied (errno 13) - SaxonC - Saxonica Developer Community - SaxonC - Saxonica Developer Community - SaxonC - Saxonica Developer Community
It is a standard way to know where the executable file located and according to the log file the user has no permission for accessing "/proc/self/exe". To verify this please ask the user to call the following command in command line: "readlink /proc/self/exe" It should return location of readlink ...
🌐
Stack Overflow
stackoverflow.com › questions › 39719479 › unable-to-use-readlink-for-proc-self-exe-for-a-c-program
shell - Unable to use readlink for /proc/self/exe for a C program - Stack Overflow
September 27, 2016 - #include<stdio.h> #include<stdlib.h> #include<errno.h> #include<sys/utsname.h> #include<string.h> #include<unistd.h> #include<sys/types.h> #include<pwd.h> #include<sys/wait.h> #include<signal.h> int main(int argc, char * argv[]) { char filename[1000]; printf("pid --- %s\n",argv[1]); sprintf(filename,"/proc/%s/status",argv[1]); FILE *f = fopen(filename, "r"); FILE *fp; char state,buf[1024]; fgets(buf,1024,f); fgets(buf,1024,f); sscanf(buf, "State: %c\n", &state); printf("process state = %c\n", state); fclose(f); char target_path[1024]; sprintf(filename, "/proc/%s/exe",argv[1]); int len = readlink (filename, target_path, sizeof (target_path)); char buffer[1024]; if(len ==-1) { perror("readlink"); } else { target_path[len] = '\0'; printf("executable path: %s\n", target_path); } return 0; }
🌐
Wikitechy
wikitechy.com › tutorials › linux › finding-current-executables-path-without-proc-self-exe
[Solved-100% Working Code] - Finding current executable's path without proc/self/exe - linux Tutorial - wikitechy
How to find current executable path without proc/self/exe ? Some OS-specific interfaces: Mac OS X: _NSGetExecutablePath() (man 3 dyld) Linux: readlink /proc/self/exe · Solaris: getexecname() FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1 · FreeBSD if it has procfs: readlink /proc/curproc/file (FreeBSD doesn't have procfs by default) NetBSD: readlink /proc/curproc/exe ·
🌐
GitHub
github.com › cooperative-computing-lab › cctools › issues › 348
`readlink /proc/self/exe` returns relative path if the executable begins with `./` under Parrot · Issue #348 · cooperative-computing-lab/cctools
January 28, 2014 - Under Parrot, if we execute some commands accessing /proc/self/exe, such as parrot_run ./ls -l /proc/self/exe and the commands begins with ./, the result of the command will be relative path, the same as the command itself. hmeng@hmeng ~...
Author   cooperative-computing-lab
🌐
LinuxQuestions.org
linuxquestions.org › questions › programming-9 › problem-on-proc-self-exe-and-proc-num-exe-478707
problem on /proc/self/exe and /proc/num/exe
In my project, I encountered a strange problem. As you know readlink(2) can be used to get the real running program by /proc/self/exe. For example: on
🌐
GitHub
github.com › AdguardTeam › AdGuardHome › issues › 4509
panic: readlink /proc/self/exe: permission denied · Issue #4509 · AdguardTeam/AdGuardHome
April 20, 2022 - Issue Details With AdGuard Home v0.107.6 I get the following error: panic: readlink /proc/self/exe: permission denied goroutine 1 [running]: github.com/AdguardTeam/AdGuardHome/internal/home.initWorkingDir({0x0, {0x0, 0x0}, {0x0, 0x0}, {0...
Author   AdguardTeam
🌐
GitHub
github.com › upx › upx › issues › 249
UPX renders /proc/self/exe useless on some systems · Issue #249 · upx/upx
February 9, 2019 - What's the problem (or question)? On some systems, UPX-compressed executables cannot read /proc/self/exe: readlink("/proc/self/exe", 0x70482804fc80, 4096) = -1 ENOENT (No such file or directory) Wh...
Author   upx
Top answer
1 of 16
398

Some OS-specific interfaces:

  • Mac OS X: _NSGetExecutablePath() (man 3 dyld)
  • Linux: readlink /proc/self/exe
  • Solaris: getexecname()
  • FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
  • FreeBSD if it has procfs: readlink /proc/curproc/file (FreeBSD doesn't have procfs by default)
  • NetBSD: readlink /proc/curproc/exe
  • DragonFly BSD: readlink /proc/curproc/file
  • Windows: GetModuleFileName() with hModule = NULL

There are also third party libraries that can be used to get this information, such as whereami as mentioned in prideout's answer, or if you are using Qt, QCoreApplication::applicationFilePath() as mentioned in the comments.

The portable (but less reliable) method is to use argv[0]. Although it could be set to anything by the calling program, by convention it is set to either a path name of the executable or a name that was found using $PATH.

Some shells, including bash and ksh, set the environment variable "_" to the full path of the executable before it is executed. In that case you can use getenv("_") to get it. However this is unreliable because not all shells do this, and it could be set to anything or be left over from a parent process which did not change it before executing your program.

2 of 16
45

The use of /proc/self/exe is non-portable and unreliable. On my Ubuntu 12.04 system, you must be root to read/follow the symlink. This will make the Boost example and probably the whereami() solutions posted fail.

This post is very long but discusses the actual issues and presents code which actually works along with validation against a test suite.

The best way to find your program is to retrace the same steps the system uses. This is done by using argv[0] resolved against file system root, pwd, path environment and considering symlinks, and pathname canonicalization. This is from memory but I have done this in the past successfully and tested it in a variety of different situations. It is not guaranteed to work, but if it doesn't you probably have much bigger problems and it is more reliable overall than any of the other methods discussed. There are situations on a Unix compatible system in which proper handling of argv[0] will not get you to your program but then you are executing in a certifiably broken environment. It is also fairly portable to all Unix derived systems since around 1970 and even some non-Unix derived systems as it basically relies on libc() standard functionality and standard command line functionality. It should work on Linux (all versions), Android, Chrome OS, Minix, original Bell Labs Unix, FreeBSD, NetBSD, OpenBSD, BSD x.x, SunOS, Solaris, SYSV, HP-UX, Concentrix, SCO, Darwin, AIX, OS X, NeXTSTEP, etc. And with a little modification probably VMS, VM/CMS, DOS/Windows, ReactOS, OS/2, etc. If a program was launched directly from a GUI environment, it should have set argv[0] to an absolute path.

Understand that almost every shell on every Unix compatible operating system that has ever been released basically finds programs the same way and sets up the operating environment almost the same way (with some optional extras). And any other program that launches a program is expected to create the same environment (argv, environment strings, etc.) for that program as if it were run from a shell, with some optional extras. A program or user can setup an environment that deviates from this convention for other subordinate programs that it launches but if it does, this is a bug and the program has no reasonable expectation that the subordinate program or its subordinates will function correctly.

Possible values of argv[0] include:

  • /path/to/executable — absolute path
  • ../bin/executable — relative to pwd
  • bin/executable — relative to pwd
  • ./foo — relative to pwd
  • executable — basename, find in path
  • bin//executable — relative to pwd, non-canonical
  • src/../bin/executable — relative to pwd, non-canonical, backtracking
  • bin/./echoargc — relative to pwd, non-canonical

Values you should not see:

  • ~/bin/executable — rewritten before your program runs.
  • ~user/bin/executable — rewritten before your program runs
  • alias — rewritten before your program runs
  • $shellvariable — rewritten before your program runs
  • *foo* — wildcard, rewritten before your program runs, not very useful
  • ?foo? — wildcard, rewritten before your program runs, not very useful

In addition, these may contain non-canonical path names and multiple layers of symbolic links. In some cases, there may be multiple hard links to the same program. For example, /bin/ls, /bin/ps, /bin/chmod, /bin/rm, etc. may be hard links to /bin/busybox.

To find yourself, follow the steps below:

  • Save pwd, PATH, and argv[0] on entry to your program (or initialization of your library) as they may change later.

  • Optional: particularly for non-Unix systems, separate out but don't discard the pathname host/user/drive prefix part, if present; the part which often precedes a colon or follows an initial "//".

  • If argv[0] is an absolute path, use that as a starting point. An absolute path probably starts with "/" but on some non-Unix systems it might start with "" or a drive letter or name prefix followed by a colon.

  • Else if argv[0] is a relative path (contains "/" or "" but doesn't start with it, such as "../../bin/foo", then combine pwd+"/"+argv[0] (use present working directory from when program started, not current).

  • Else if argv[0] is a plain basename (no slashes), then combine it with each entry in PATH environment variable in turn and try those and use the first one which succeeds.

  • Optional: Else try the very platform specific /proc/self/exe, /proc/curproc/file (BSD), and (char *)getauxval(AT_EXECFN), and dlgetname(...) if present. You might even try these before argv[0]-based methods, if they are available and you don't encounter permission issues. In the somewhat unlikely event (when you consider all versions of all systems) that they are present and don't fail, they might be more authoritative.

  • Optional: check for a path name passed in using a command line parameter.

  • Optional: check for a pathname in the environment explicitly passed in by your wrapper script, if any.

  • Optional: As a last resort try environment variable "_". It might point to a different program entirely, such as the users shell.

  • Resolve symlinks, there may be multiple layers. There is the possibility of infinite loops, though if they exist your program probably won't get invoked.

  • Canonicalize filename by resolving substrings like "/foo/../bar/" to "/bar/". Note this may potentially change the meaning if you cross a network mount point, so canonization is not always a good thing. On a network server, ".." in symlink may be used to traverse a path to another file in the server context instead of on the client. In this case, you probably want the client context so canonicalization is ok. Also convert patterns like "/./" to "/" and "//" to "/". In shell, readlink --canonicalize will resolve multiple symlinks and canonicalize name. Chase may do similar but isn't installed. realpath() or canonicalize_file_name(), if present, may help.

If realpath() doesn't exist at compile time, you might borrow a copy from a permissively licensed library distribution, and compile it in yourself rather than reinventing the wheel. Fix the potential buffer overflow (pass in sizeof output buffer, think strncpy() vs strcpy()) if you will be using a buffer less than PATH_MAX. It may be easier just to use a renamed private copy rather than testing if it exists. Permissive license copy from android/darwin/bsd: https://android.googlesource.com/platform/bionic/+/f077784/libc/upstream-freebsd/lib/libc/stdlib/realpath.c

Be aware that multiple attempts may be successful or partially successful and they might not all point to the same executable, so consider verifying your executable; however, you may not have read permission — if you can't read it, don't treat that as a failure. Or verify something in proximity to your executable such as the "../lib/" directory you are trying to find. You may have multiple versions, packaged and locally compiled versions, local and network versions, and local and USB-drive portable versions, etc. and there is a small possibility that you might get two incompatible results from different methods of locating. And "_" may simply point to the wrong program.

A program using execve can deliberately set argv[0] to be incompatible with the actual path used to load the program and corrupt PATH, "_", pwd, etc. though there isn't generally much reason to do so; but this could have security implications if you have vulnerable code that ignores the fact that your execution environment can be changed in variety of ways including, but not limited, to this one (chroot, fuse filesystem, hard links, etc.) It is possible for shell commands to set PATH but fail to export it.

You don't necessarily need to code for non-Unix systems but it would be a good idea to be aware of some of the peculiarities so you can write the code in such a way that it isn't as hard for someone to port later. Be aware that some systems (DEC VMS, DOS, URLs, etc.) might have drive names or other prefixes which end with a colon such as "C:", "sys$drive:[foo]bar", and "file:///foo/bar/baz". Old DEC VMS systems use "[" and "]" to enclose the directory portion of the path though this may have changed if your program is compiled in a POSIX environment. Some systems, such as VMS, may have a file version (separated by a semicolon at the end). Some systems use two consecutive slashes as in "//drive/path/to/file" or "user@host:/path/to/file" (scp command) or "file://hostname/path/to/file" (URL). In some cases (DOS and Windows), PATH might have different separator characters — ";" vs ":" and "" vs "/" for a path separator. In csh/tsh there is "path" (delimited with spaces) and "PATH" delimited with colons but your program should receive PATH so you don't need to worry about path. DOS and some other systems can have relative paths that start with a drive prefix. C:foo.exe refers to foo.exe in the current directory on drive C, so you do need to lookup current directory on C: and use that for pwd.

An example of symlinks and wrappers on my system:

/usr/bin/google-chrome is symlink to
/etc/alternatives/google-chrome  which is symlink to
/usr/bin/google-chrome-stable which is symlink to
/opt/google/chrome/google-chrome which is a bash script which runs
/opt/google/chome/chrome

Note that user bill posted a link above to a program at HP that handles the three basic cases of argv[0]. It needs some changes, though:

  • It will be necessary to rewrite all the strcat() and strcpy() to use strncat() and strncpy(). Even though the variables are declared of length PATHMAX, an input value of length PATHMAX-1 plus the length of concatenated strings is > PATHMAX and an input value of length PATHMAX would be unterminated.
  • It needs to be rewritten as a library function, rather than just to print out results.
  • It fails to canonicalize names (use the realpath code I linked to above)
  • It fails to resolve symbolic links (use the realpath code)

So, if you combine both the HP code and the realpath code and fix both to be resistant to buffer overflows, then you should have something which can properly interpret argv[0].

The following illustrates actual values of argv[0] for various ways of invoking the same program on Ubuntu 12.04. And yes, the program was accidentally named echoargc instead of echoargv. This was done using a script for clean copying but doing it manually in shell gets same results (except aliases don't work in script unless you explicitly enable them).

cat ~/src/echoargc.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
main(int argc, char **argv)
{
  printf("  argv[0]=\"%s\"\n", argv[0]);
  sleep(1);  /* in case run from desktop */
}
tcc -o ~/bin/echoargc ~/src/echoargc.c
cd ~
/home/whitis/bin/echoargc
  argv[0]="/home/whitis/bin/echoargc"
echoargc
  argv[0]="echoargc"
bin/echoargc
  argv[0]="bin/echoargc"
bin//echoargc
  argv[0]="bin//echoargc"
bin/./echoargc
  argv[0]="bin/./echoargc"
src/../bin/echoargc
  argv[0]="src/../bin/echoargc"
cd ~/bin
*echo*
  argv[0]="echoargc"
e?hoargc
  argv[0]="echoargc"
./echoargc
  argv[0]="./echoargc"
cd ~/src
../bin/echoargc
  argv[0]="../bin/echoargc"
cd ~/junk
~/bin/echoargc
  argv[0]="/home/whitis/bin/echoargc"
~whitis/bin/echoargc
  argv[0]="/home/whitis/bin/echoargc"
alias echoit=~/bin/echoargc
echoit
  argv[0]="/home/whitis/bin/echoargc"
echoarg=~/bin/echoargc
$echoarg
  argv[0]="/home/whitis/bin/echoargc"
ln -s ~/bin/echoargc junk1
./junk1
  argv[0]="./junk1"
ln -s /home/whitis/bin/echoargc junk2
./junk2
  argv[0]="./junk2"
ln -s junk1 junk3
./junk3
  argv[0]="./junk3"


gnome-desktop-item-edit --create-new ~/Desktop
# interactive, create desktop link, then click on it
  argv[0]="/home/whitis/bin/echoargc"
# interactive, right click on gnome application menu, pick edit menus
# add menu item for echoargc, then run it from gnome menu
 argv[0]="/home/whitis/bin/echoargc"

 cat ./testargcscript 2>&1 | sed -e 's/^/    /g'
#!/bin/bash
# echoargc is in ~/bin/echoargc
# bin is in path
shopt -s expand_aliases
set -v
cat ~/src/echoargc.c
tcc -o ~/bin/echoargc ~/src/echoargc.c
cd ~
/home/whitis/bin/echoargc
echoargc
bin/echoargc
bin//echoargc
bin/./echoargc
src/../bin/echoargc
cd ~/bin
*echo*
e?hoargc
./echoargc
cd ~/src
../bin/echoargc
cd ~/junk
~/bin/echoargc
~whitis/bin/echoargc
alias echoit=~/bin/echoargc
echoit
echoarg=~/bin/echoargc
$echoarg
ln -s ~/bin/echoargc junk1
./junk1
ln -s /home/whitis/bin/echoargc junk2
./junk2
ln -s junk1 junk3
./junk3

These examples illustrate that the techniques described in this post should work in a wide range of circumstances and why some of the steps are necessary.

EDIT: Now, the program that prints argv[0] has been updated to actually find itself.

// Copyright 2015 by Mark Whitis.  License=MIT style
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <assert.h>
#include <string.h>
#include <errno.h>

// "look deep into yourself, Clarice"  -- Hanibal Lector
char findyourself_save_pwd[PATH_MAX];
char findyourself_save_argv0[PATH_MAX];
char findyourself_save_path[PATH_MAX];
char findyourself_path_separator='/';
char findyourself_path_separator_as_string[2]="/";
char findyourself_path_list_separator[8]=":";  // could be ":; "
char findyourself_debug=0;

int findyourself_initialized=0;

void findyourself_init(char *argv0)
{

  getcwd(findyourself_save_pwd, sizeof(findyourself_save_pwd));

  strncpy(findyourself_save_argv0, argv0, sizeof(findyourself_save_argv0));
  findyourself_save_argv0[sizeof(findyourself_save_argv0)-1]=0;

  strncpy(findyourself_save_path, getenv("PATH"), sizeof(findyourself_save_path));
  findyourself_save_path[sizeof(findyourself_save_path)-1]=0;
  findyourself_initialized=1;
}


int find_yourself(char *result, size_t size_of_result)
{
  char newpath[PATH_MAX+256];
  char newpath2[PATH_MAX+256];

  assert(findyourself_initialized);
  result[0]=0;

  if(findyourself_save_argv0[0]==findyourself_path_separator) {
    if(findyourself_debug) printf("  absolute path\n");
     realpath(findyourself_save_argv0, newpath);
     if(findyourself_debug) printf("  newpath=\"%s\"\n", newpath);
     if(!access(newpath, F_OK)) {
        strncpy(result, newpath, size_of_result);
        result[size_of_result-1]=0;
        return(0);
     } else {
    perror("access failed 1");
      }
  } else if( strchr(findyourself_save_argv0, findyourself_path_separator )) {
    if(findyourself_debug) printf("  relative path to pwd\n");
    strncpy(newpath2, findyourself_save_pwd, sizeof(newpath2));
    newpath2[sizeof(newpath2)-1]=0;
    strncat(newpath2, findyourself_path_separator_as_string, sizeof(newpath2));
    newpath2[sizeof(newpath2)-1]=0;
    strncat(newpath2, findyourself_save_argv0, sizeof(newpath2));
    newpath2[sizeof(newpath2)-1]=0;
    realpath(newpath2, newpath);
    if(findyourself_debug) printf("  newpath=\"%s\"\n", newpath);
    if(!access(newpath, F_OK)) {
        strncpy(result, newpath, size_of_result);
        result[size_of_result-1]=0;
        return(0);
     } else {
    perror("access failed 2");
      }
  } else {
    if(findyourself_debug) printf("  searching $PATH\n");
    char *saveptr;
    char *pathitem;
    for(pathitem=strtok_r(findyourself_save_path, findyourself_path_list_separator,  &saveptr); pathitem; pathitem=strtok_r(NULL, findyourself_path_list_separator, &saveptr) ) {
       if(findyourself_debug>=2) printf("pathitem=\"%s\"\n", pathitem);
       strncpy(newpath2, pathitem, sizeof(newpath2));
       newpath2[sizeof(newpath2)-1]=0;
       strncat(newpath2, findyourself_path_separator_as_string, sizeof(newpath2));
       newpath2[sizeof(newpath2)-1]=0;
       strncat(newpath2, findyourself_save_argv0, sizeof(newpath2));
       newpath2[sizeof(newpath2)-1]=0;
       realpath(newpath2, newpath);
       if(findyourself_debug) printf("  newpath=\"%s\"\n", newpath);
      if(!access(newpath, F_OK)) {
          strncpy(result, newpath, size_of_result);
          result[size_of_result-1]=0;
          return(0);
      }
    } // end for
    perror("access failed 3");

  } // end else
  // if we get here, we have tried all three methods on argv[0] and still haven't succeeded.   Include fallback methods here.
  return(1);
}

main(int argc, char **argv)
{
  findyourself_init(argv[0]);

  char newpath[PATH_MAX];
  printf("  argv[0]=\"%s\"\n", argv[0]);
  realpath(argv[0], newpath);
  if(strcmp(argv[0],newpath)) { printf("  realpath=\"%s\"\n", newpath); }
  find_yourself(newpath, sizeof(newpath));
  if(1 || strcmp(argv[0],newpath)) { printf("  findyourself=\"%s\"\n", newpath); }
  sleep(1);  /* in case run from desktop */
}

And here is the output which demonstrates that in every one of the previous tests it actually did find itself.

tcc -o ~/bin/echoargc ~/src/echoargc.c
cd ~
/home/whitis/bin/echoargc
  argv[0]="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
echoargc
  argv[0]="echoargc"
  realpath="/home/whitis/echoargc"
  findyourself="/home/whitis/bin/echoargc"
bin/echoargc
  argv[0]="bin/echoargc"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
bin//echoargc
  argv[0]="bin//echoargc"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
bin/./echoargc
  argv[0]="bin/./echoargc"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
src/../bin/echoargc
  argv[0]="src/../bin/echoargc"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
cd ~/bin
*echo*
  argv[0]="echoargc"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
e?hoargc
  argv[0]="echoargc"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
./echoargc
  argv[0]="./echoargc"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
cd ~/src
../bin/echoargc
  argv[0]="../bin/echoargc"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
cd ~/junk
~/bin/echoargc
  argv[0]="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
~whitis/bin/echoargc
  argv[0]="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
alias echoit=~/bin/echoargc
echoit
  argv[0]="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
echoarg=~/bin/echoargc
$echoarg
  argv[0]="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
rm junk1 junk2 junk3
ln -s ~/bin/echoargc junk1
./junk1
  argv[0]="./junk1"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
ln -s /home/whitis/bin/echoargc junk2
./junk2
  argv[0]="./junk2"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"
ln -s junk1 junk3
./junk3
  argv[0]="./junk3"
  realpath="/home/whitis/bin/echoargc"
  findyourself="/home/whitis/bin/echoargc"

The two GUI launches described above also correctly find the program.

There is one potential pitfall. The access() function drops permissions if the program is setuid before testing. If there is a situation where the program can be found as an elevated user but not as a regular user, then there might be a situation where these tests would fail, although it is unlikely the program could actually be executed under those circumstances. One could use euidaccess() instead. It is possible, however, that it might find an inaccessable program earlier on path than the actual user could.

🌐
GitHub
github.com › VividCortex › godaemon › issues › 24
readlink /proc/self/exe: no such file or directory · Issue #24 · VividCortex/godaemon
April 24, 2017 - This happened twice: 2017/04/24 20:26:59 readlink /proc/self/exe: no such file or directory 2017/04/24 20:26:59 readlink /proc/self/exe: no such file or directory and then my app is not daemonized
Author   VividCortex
🌐
Lindevs
lindevs.com › get-executable-file-path-on-linux-using-cpp
Get Executable File Path on Linux using C++ | Lindevs
October 20, 2023 - The provided code retrieves and prints the absolute path of the executable file being run on a Linux system: #include <iostream> #include <climits> #include <unistd.h> int main() { char path[PATH_MAX + 1]; ssize_t length = readlink("/proc/self/exe", path, PATH_MAX); path[length] = '\0'; std::cout << path << std::endl; return 0; }
🌐
Programmersought
programmersought.com › article › 26056395174
readlink and /proc/self/exe - Programmer Sought
ssize_t readlink(const char *path, char *buf, size_t bufsiz); /proc/self/exe is a symbolic link, representing the absolute path of the current program Use readlink to read /proc/self/exe to get the absolute path of the current program