csymlinkreadlink

Why C readlink() has ELOOP as a possible error


Background

I read about the Open Group Specification about readlink(), and there is an error called ELOOP, which indicates "A loop exists in symbolic links encountered during resolution of the path argument.", so I assume this function will continue path resolution until encountering a non-link file.

However, I did an experiment and found that readlink() only resolve the passed in path argument and just stops there but not keep resolving until reaching a non-link file.

My Problem

  1. If it's for realpath(), that makes all the sense to have ELOOP as a possible error. But why does ELOOP even exist for readlink() while it only resolves the path once?
  2. I saw this on the spec "The [ELOOP] optional error condition is added to align with the IEEE P1003.1a draft standard", does that mean the behavior of readlink() (whether it keeps resolving until reaching a non-link file) depends on implementation?

my gcc version is 8.2.1


Solution

  • readlink gives you the immediate target of a symbolic link. But what if resolving the path to the symbolic link involves another symlink?

    Take readlink("/foo/bar") as an example. It's supposed to return the link target of bar, but if /foo is a symlink pointing to itself, you'll get ELOOP because readlink has to resolve the directory part before getting to the final entry.

    See also man path_resolution.