How to implement readlink to find the path

后端 未结 5 1936
悲&欢浪女
悲&欢浪女 2020-12-09 03:33

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

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-09 04:08

    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 as follow for this purpose:

    std::string get_selfpath()
    {
        std::vector 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 "";
    }
    

提交回复
热议问题