How to find what symlink points to?

Mel Flynn mel.flynn+fbsd.questions at mailing.thruhere.net
Mon Jul 27 17:25:21 UTC 2009


On Monday 27 July 2009 05:45:13 Unga wrote:

> > > Hi all
> > >
> > > I need to remove some unwanted symlinks on /dev using
> >
> > a C program.
> >
> > > The "struct dirent" only shows the symlink name, how
> >
> > do I find what that
> >
> > > symlink points to for verification purpose?
> >
> > By using the readlink(2) system call.
>
> But readlink(2) fails with errno set to 2. Can readlink(2) use with dev
> nodes?

Works for me. errno 2 is ENOENT ("No such file or directory"). I would inspect 
if your request path points to the right location.

% ./rl /dev/stderr
/dev/stderr => fd/2

% cat rl.c
#include <sys/types.h>
#include <sys/param.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <err.h>

int main(int argc, char **argv)
{
        char path[MAXPATHLEN], buf[MAXPATHLEN+1];
        ssize_t res;

        if( argc != 2 )
                exit(67);

        (void)strlcpy(path, argv[1], sizeof(path));
        res = readlink(path, buf, sizeof(buf));
        if( res < 0 )
                err(EXIT_FAILURE, "readlink()");
        buf[MAXPATHLEN] = '\0';
        printf("%s => %s\n", path, buf);

        return (0);
}

-- 
Mel


More information about the freebsd-questions mailing list