Note that there are some explanatory texts on larger screens.

plurals
  1. POHowto use readlink with dynamic memory allocation
    primarykey
    data
    text
    <h2>Problem:</h2> <p>On a linux machine I want to read the target string of a link. From documentation I have found the following code sample (without error processing):</p> <pre><code>struct stat sb; ssize_t r; char * linkname; lstat("&lt;some link&gt;", &amp;sb); linkname = malloc(sb.st_size + 1); r = readlink("/proc/self/exe", linkname, sb.st_size + 1); </code></pre> <p>The probelm is that sb.st_size returns 0 for links on my system.</p> <p>So how does one allocate memory dynamically for readline on such systems?</p> <p>Many thanks!</p> <hr> <h2>One possible solution:</h2> <p>For future reference. Using the points made by jilles:</p> <pre><code>struct stat sb; ssize_t r = INT_MAX; int linkSize = 0; const int growthRate = 255; char * linkTarget = NULL; // get length of the pathname the link points to if (lstat("/proc/self/exe", &amp;sb) == -1) { // could not lstat: insufficient permissions on directory? perror("lstat"); return; } // read the link target into a string linkSize = sb.st_size + 1 - growthRate; while (r &gt;= linkSize) { // i.e. symlink increased in size since lstat() or non-POSIX compliant filesystem // allocate sufficient memory to hold the link linkSize += growthRate; free(linkTarget); linkTarget = malloc(linkSize); if (linkTarget == NULL) { // insufficient memory fprintf(stderr, "setProcessName(): insufficient memory\n"); return; } // read the link target into variable linkTarget r = readlink("/proc/self/exe", linkTarget, linkSize); if (r &lt; 0) { // readlink failed: link was deleted? perror("lstat"); return; } } linkTarget[r] = '\0'; // readlink does not null-terminate the string </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload