dirs_links/bad_symlink.c

This is dirs_links/bad_symlink.c, an example to accompany the book, The Linux Programming Interface.

This file is not printed in the book; it is the solution to Exercise 18-2 (page 373).

The source code file is copyright 2024, Michael Kerrisk, and is licensed under the GNU General Public License, version 3.

In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.

 

Download dirs_links/bad_symlink.c

  Cover of The Linux Programming Interface

Function list (Bold in this list means a function is not static)

/* bad_symlink.c

   The following code demonstrates a mistake in using symlink(): the link
   is created with an incorrect relative path, and the subsequent chmod()
   call fails. Note: symbolic links are interpreted relative to the directory
   in which they reside, not the current directory of the process.
*/
#include <sys/stat.h>
#include <fcntl.h>
#include "tlpi_hdr.h"
int
main(int argc, char *argv[])
{
    if (mkdir("test", S_IRUSR | S_IWUSR | S_IXUSR) == -1)
        errExit("mkdir");
    if (chdir("test") == -1)
        errExit("chdir");

    int fd = open("myfile", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
    if (fd == -1)
        errExit("open");
    if (close(fd) == -1)
        errExit("close");

    if (symlink("myfile", "../mylink") == -1)
        errExit("symlink");
    if (chmod("../mylink", S_IRUSR) == -1)
        errExit("chmod");

    exit(EXIT_SUCCESS);
}

 

Download dirs_links/bad_symlink.c

Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.

Valid XHTML 1.1