How to write a current directory finder?

Guy Harris guy at auspex.auspex.com
Sun Apr 2 18:59:11 AEST 1989


>Starting with `.', get the device and i-node numbers of each directory, back
>up to `..', search the directory, checking each file for matching numbers,
>and when one is found, add its name to the beginning of the path.
>Then, get the device and i-node numbers of that directory, back up to its
>parent, and search for matching numbers, repeating until a directory and its
>parent have the same device and i-node numbers (because /.. is /).

That's more-or-less what the 4.3BSD "getwd" does.

>Since my function is about 10 times slower than /bin/pwd, this is obviously
>not the optimum method.
>
>Since the manpage for `getwd' on my system (Sun Unix 3.2) warns that a
>failing `getwd' call may leave the current directory in the wrong place, I
>assume that `getwd' moves around in the process of figuring it out.

The 4.2BSD version did that (the SunOS 3.2 version is based on the
4.2BSD one).  "/bin/pwd" in 4.[23]BSD and SunOS (and probably in other
systems that picked it up from 4.[23]BSD) just calls "getwd" and prints
the result.

>But I don't see how this helps, using the same basic logic as my method.
>You trade time constructing a big `../../../../..' name and using that in
>all the lookups for moving around and cutting out all the `..'s.
>But can that really make such a difference?

Yes, since it avoids several levels of lookup; looking up "..", for
example, is cheaper than looking up "../../../../..".  Directory-name
lookup caching (which 4.3BSD provides) helps, but it can't eliminate the
performance hit entirely (you still have to copy longer pathnames into
the kernel on typical UNIX systems, and still have to do some work on
each component, even if you don't have to scan the directory).



More information about the Comp.unix.wizards mailing list