Real path of soft links with missing target

Roger Riggs roger.riggs at oracle.com
Wed Jul 20 18:31:29 UTC 2022


Hi,

If realpath fails, there is no actual file with that path.

The application could fallback to reading the symbolic link and then it 
would know the difference.

$.02, Roger

On 7/20/22 2:19 PM, maxxedev at gmail.com wrote:
> Ah, how about readlink[3]?
>
>      #include <limits.h>
>      #include <stdlib.h>
>      #include <stdio.h>
>      #include <errno.h>
>      #include <unistd.h>
>
>      int main(int argc, char** argv) {
>       char* path = "foo-source";
>       char resolved[PATH_MAX + 1] = {0};
>       printf("%d\n", readlink(path, resolved, sizeof(resolved))); // 10 bytes
>       printf("%d\n", errno); // 0
>       printf("%s\n", resolved);   // "foo-target"
>       return 0;
>      }
>
> Motivation is: how could one replicate "ls -l" functionality in Java?
> "ls -l" does show the link target even if it's missing.
>
> [3] https://pubs.opengroup.org/onlinepubs/009696699/functions/readlink.html
>
>
> On Wed, Jul 20, 2022 at 10:41 AM Brian Burkhalter
> <brian.burkhalter at oracle.com> wrote:
>>
>> On Jul 20, 2022, at 10:16 AM, maxxedev at gmail.com wrote:
>>
>>     #include <limits.h>
>>     #include <stdlib.h>
>>     #include <stdio.h>
>>     #include <errno.h>
>>
>>     int main(int argc, char** argv) {
>>         char* path = "foo-source";
>>         char resolved[PATH_MAX + 1] = {0};
>>         char* result = realpath(path, resolved);
>>         printf("%d\n", result == NULL);  // 1
>>         printf("%d\n", errno == ENOENT); // 1
>>         printf("%s\n", resolved);   // "foo-target"
>>         return 0;
>>     }
>>
>>
>> When I run the above code in /tmp/ on Ubuntu 22.04 as
>>
>> $ ln -s foo-target foo-source
>> $ ./resolve
>>
>> it prints
>>
>> 1
>> 1
>> /tmp/foo-target
>>
>> As realpath(3) states
>>
>> “[If there is an error, ] it returns NULL, the contents of the array resolved_path are undefined, and errno is set to indicate the error.”
>>
>> I don’t think one can rely on resolved_path or the return value when there is an error so I don’t know what we could do here. That resolved_path ends up being the link seems like an artifact that one cannot count on.
>>
>> Brian
>>
>>
>>



More information about the nio-dev mailing list