How to implement readlink to find the path

后端 未结 5 1942
悲&欢浪女
悲&欢浪女 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 03:56

    #include 
    #include 
    
    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 
    
    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().

提交回复
热议问题