27

Using the readlink function used as a solution to How do I find the location of the executable in C?, how would I get the path into a char array? Also, what do the variables buf and bufsize represent and how do I initialize them?

EDIT: I am trying to get the path of the currently running program, just like the question linked above. The answer to that question said to use readlink("proc/self/exe"). I do not know how to implement that into my program. I tried:

char buf[1024];  
string var = readlink("/proc/self/exe", buf, bufsize);  

This is obviously incorrect.

Community
  • 1
  • 1
a sandwhich
  • 4,352
  • 12
  • 41
  • 62

5 Answers5

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;
}
Mat
  • 202,337
  • 40
  • 393
  • 406
  • No, sorry, I guess I didn't phrase my sentence correctly. I don't have the path, I am using readlink("/proc/self/exe", buf, bufsize); correctly in order to retrieve it. – a sandwhich Apr 02 '11 at 21:35
  • I don't understand what you're saying. Please edit your question to show what you have, and an example of what you want. – Mat Apr 02 '11 at 21:39
  • ok, I put more details in, but my original answer worked quite well with a fixed path... – Mat Apr 02 '11 at 21:54
  • Just to add some details on which I've been struggling a bit: the `get_selfPath()` function returns the path including the executable name. To get just the path removing the exe name you can do the following: `std::string::size_type t = path.find_last_of("/")` and then `path = path.substr(0,t)`. I don't know why everywhere this is never clarified enough;) – merosss May 03 '14 at 15:47
  • @a.lasram: that's not a typo at all. – Mat Nov 01 '14 at 11:31
  • @Mat : what should be the value of the argument of the function `do_readlink`? – Jackzz Feb 05 '15 at 09:29
  • I don't think it's a good idea to be so cavalier about allocating 4KiB on the stack like that. Why not an `std::vector`? – einpoklum Nov 27 '16 at 15:34
  • You don't need to add mess about with adding a null terminator. Just write `if (len != -1) { return std::string(buff, static_cast(len)); }` – Ryan Burn Dec 12 '18 at 18:52
  • @einpoklum Because `readlink` is a low-level sys-call that doesn't have access to `std::vector` or even `malloc`. If you're really concerned about stack space, you could just put the buffer in static storage instead: `static thread_local char buff[PATH_MAX];`. – yyny Feb 21 '20 at 17:38
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 "";
}
Wddysr
  • 86
  • 1
  • 5
4

Let's look at what the manpage says:

 readlink() places the contents of the symbolic link path in the buffer
 buf, which has size bufsiz.  readlink does not append a NUL character to
 buf.

OK. Should be simple enough. Given your buffer of 1024 chars:

 char buf[1024];

 /* The manpage says it won't null terminate.  Let's zero the buffer. */
 memset(buf, 0, sizeof(buf));

 /* Note we use sizeof(buf)-1 since we may need an extra char for NUL. */
 if (readlink("/proc/self/exe", buf, sizeof(buf)-1) < 0)
 {
    /* There was an error...  Perhaps the path does not exist
     * or the buffer is not big enough.  errno has the details. */
    perror("readlink");
    return -1;
 }
asveikau
  • 39,039
  • 2
  • 53
  • 68
2
char *
readlink_malloc (const char *filename)
{
  int size = 100;
  char *buffer = NULL;

  while (1)
    {
      buffer = (char *) xrealloc (buffer, size);
      int nchars = readlink (filename, buffer, size);
      if (nchars < 0)
        {
          free (buffer);
          return NULL;
        }
      if (nchars < size)
        return buffer;
      size *= 2;
    }
}

Taken from: http://www.delorie.com/gnu/docs/glibc/libc_279.html

1
#include <stdlib.h>
#include <unistd.h>

static char *exename(void)
{
    char *buf;
    char *newbuf;
    size_t cap;
    ssize_t len;

    buf = NULL;
    for (cap = 64; cap <= 16384; cap *= 2) {
        newbuf = realloc(buf, cap);
        if (newbuf == NULL) {
            break;
        }
        buf = newbuf;
        len = readlink("/proc/self/exe", buf, cap);
        if (len < 0) {
            break;
        }
        if ((size_t)len < cap) {
            buf[len] = 0;
            return buf;
        }
    }
    free(buf);
    return NULL;
}

#include <stdio.h>

int main(void)
{
    char *e = exename();
    printf("%s\n", e ? e : "unknown");
    free(e);
    return 0;
}

This uses the traditional "when you don't know the right buffer size, reallocate increasing powers of two" trick. We assume that allocating less than 64 bytes for a pathname is not worth the effort. We also assume that an executable pathname as long as 16384 (2**14) bytes has to indicate some kind of anomaly in how the program was installed, and it's not useful to know the pathname as we'll soon encounter bigger problems to worry about.

There is no need to bother with constants like PATH_MAX. Reserving so much memory is overkill for almost all pathnames, and as noted in another answer, it's not guaranteed to be the actual upper limit anyway. For this application, we can pick a common-sense upper limit such as 16384. Even for applications with no common-sense upper limit, reallocating increasing powers of two is a good approach. You only need log n calls for a n-byte result, and the amount of memory capacity you waste is proportional to the length of the result. It also avoids race conditions where the length of the string changes between the realloc() and the readlink().

Lassi
  • 3,522
  • 3
  • 22
  • 34