Page MenuHomeFreeBSD

symlink.c: an example of using O_PATH to read symlink

Authored By
kib
Sun, Feb 8, 1:23 AM
Size
975 B
Referenced Files
None
Subscribers
None

symlink.c: an example of using O_PATH to read symlink

/* $Id: symlink.c,v 1.3 2026/02/08 01:21:51 kostik Exp kostik $ */
#include <sys/stat.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
static void
onelink(const char *name)
{
struct stat st;
long plen;
ssize_t llen;
int fd;
fd = open(name, O_PATH | O_NOFOLLOW);
if (fd == -1) {
warn("open \"%s\"", name);
return;
}
if (fstatat(fd, "", &st, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW) == -1) {
warn("fstatat \"%s\"", name);
goto ret;
}
if (!S_ISLNK(st.st_mode)) {
warnx("%s: not a symlink", name);
goto ret;
}
plen = fpathconf(fd, _PC_SYMLINK_MAX);
if (plen == -1) {
warn("pathconf \"%s\"", name);
goto ret;
}
{
char path[plen + 1];
llen = readlinkat(fd, "", path, plen);
if (llen == -1) {
warn("readlinkat \"%s\"", name);
goto ret;
}
path[llen] = '\0';
printf("%s => %s\n", name, path);
}
ret:
close(fd);
}
int
main(int argc, char *argv[])
{
for (int i = 1; i < argc; i++)
onelink(argv[i]);
}

File Metadata

Mime Type
text/plain; charset=utf-8
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
28520474
Default Alt Text
symlink.c: an example of using O_PATH to read symlink (975 B)

Event Timeline