[cs631apue] ls(1) symbolic link issue

Jan Schaumann jschauma at stevens.edu
Sun Oct 14 21:53:37 EDT 2018

Ramana Nagasamudram <rnagasam at stevens.edu> wrote:
> I've tried using readlink(2) and realpath(3) to find the name of
> the target of a symbolic link.  readlink(2) fails when the target
> doesn't exist.

That sounds like you're giving readlink not the name of the symlink, but
the name of the target of the symlink.  This may be because somewhere
along the line you used e.g. stat(2) instead of lstat(2) or an
equivalent function to identify the pathname or filename.

readlink(2) itself does not care at all about whether the target of the
file it's inspecting exists or not.

Here's an example:

$ cat >readlink-test.c <<EOF
#include <sys/param.h>

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv) {
	int i;
	char buf[MAXPATHLEN];

	for (i = 1; i < argc; i++) {
		if ((readlink(argv[i], buf, MAXPATHLEN) < 0)) {
			fprintf(stderr, "Unable to open '%s': %s\n", argv[i], strerror(errno));
		printf("%s -> %s\n", argv[i], buf);
		bzero(buf, MAXPATHLEN);

	return 0;
$ cc -Wall -Wextra -Werror readlink-test.c
$ ln -s /nowhere file1
$ ln -s nowhere file2
$ ln -s /nowhere/ file3
$ ls -lh file*
$ lrwx------  1 jschauma  wheel    8B Oct 14 21:44 file1 -> /nowhere
$ lrwx------  1 jschauma  wheel    7B Oct 14 21:44 file2 -> nowhere
$ lrwx------  1 jschauma  wheel    9B Oct 14 21:44 file3 -> /nowhere/
$ ./a.out file*
file1 -> /nowhere
file2 -> nowhere
file3 -> /nowhere/

Check what you're passing as the first arg to readlink(2)...


More information about the cs631apue mailing list