Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

122 Files and Directories Chapter 4


This creates a directoryfoothat contains the fileaand a symbolic link that points to
foo.Weshow this arrangement in Figure4.18, drawing a directory as a circle and a file
as a square.

foo

a testdir

Figure 4.18Symbolic linktestdirthat creates a loop

If we write a simple program that uses the standardfunctionftw( 3 )on Solaris to
descend through a file hierarchy,printing each pathname encountered, the output is
foo
foo/a
foo/testdir
foo/testdir/a
foo/testdir/testdir
foo/testdir/testdir/a
foo/testdir/testdir/testdir
foo/testdir/testdir/testdir/a
(many morelines until we encounter anELOOPerror)
In Section 4.22, we provide our own version of theftwfunction that useslstat
instead ofstat, to prevent it from following symbolic links.

Note that on Linux, theftwandnftwfunctions recordall directories seen and avoid
processing a directory morethan once, so they don’t display this behavior.

Aloop of this form is easy to remove. Wecanunlinkthe filefoo/testdir,as
unlinkdoes not follow a symbolic link. But if we create a hardlink that forms a loop
of this type, its removal is much moredifficult. This is why thelinkfunction will not
form a hardlink to a directory unless the process has superuser privileges.

Indeed, Rich Stevens did this on his own system as an experiment while writing the original
version of this section. The file system got corrupted and the normalfsck( 1 )utility couldn’t
fix things. The deprecated toolsclri( 8 )anddcheck( 8 )wereneeded to repair the file system.
The need for hardlinks to directories has long since passed. With symbolic links and the
mkdirfunction, there is no longer any need for users to create hardlinks to directories.

When we open a file, if the pathname passed toopenspecifies a symbolic link,
openfollows the link to the specified file. If the file pointed to by the symbolic link
doesn’t exist,openreturns an error saying that it can’t open the file. This response can
confuse users who aren’t familiar with symbolic links. For example,
Free download pdf