UNLINK(3P)

๐ŸŒธ PROLOG ๐ŸŒธ

okay bestie, real talk: this manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. So like, vibe check your local Linux page if you're on Linux, because no cap, the implementation can be different. This is the unlink(3P) page, and we're about to make it make sense. ๐Ÿ’–


โœจ NAME โœจ

unlink, unlinkat โ€” remove a directory entry. periodt. ๐Ÿ’…


๐ŸŽ€ SYNOPSIS ๐ŸŽ€

#include <unistd.h>

int unlink(const char *path);
#include <fcntl.h>

int unlinkat(int fd, const char *path, int flag);

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

The unlink() function shall remove a link to a file. If path names a symbolic link, unlink() shall remove the symbolic link named by path and shall not affect any file or directory named by the contents of the symbolic link. Otherwise, unlink() shall remove the link named by the pathname pointed to by path and shall decrement the link count of the file referenced by the link. so if it's a symlink, the symlink itself gets removed and the thing it points to is untouched ๐Ÿ˜ญ

When the file's link count becomes 0 and no process has the file open, the space occupied by the file shall be freed and the file shall no longer be accessible. If one or more processes have the file open when the last link is removed, the link shall be removed before unlink() returns, but the removal of the file contents shall be postponed until all references to the file are closed. link count hits 0 and nobody has it open? space freed, file gone. but if someone still has it open, the link dips before unlink() returns, and the contents stick around until all references close ๐Ÿซถ

The path argument shall not name a directory unless the process has appropriate privileges and the implementation supports using unlink() on directories. path can't name a directory unless you have the right privileges and the implementation even supports unlink() on directories ๐Ÿ™ˆ

Upon successful completion, unlink() shall mark for update the last data modification and last file status change timestamps of the parent directory. Also, if the file's link count is not 0, the last file status change timestamp of the file shall be marked for update. on success, parent directory's last data modification and last file status change timestamps get marked for update. and if the file's link count isn't 0, the file's last file status change timestamp gets marked too โญ

The unlinkat() function shall be equivalent to the unlink() or rmdir() function except in the case where path specifies a relative path. In this case the directory entry to be removed is determined relative to the directory associated with the file descriptor fd instead of the current working directory. If the access mode of the open file description associated with the file descriptor is not O_SEARCH, the function shall check whether directory searches are permitted using the current permissions of the directory underlying the file descriptor. If the access mode is O_SEARCH, the function shall not perform the check. unlinkat() is like unlink() or rmdir(), but if path is relative, it resolves relative to the directory tied to fd, not the current working directory. if the fd's open file description access mode isn't O_SEARCH, it checks if directory searches are allowed using the current permissions of the directory under fd. if it is O_SEARCH, no check ๐Ÿ’…

Values for flag are constructed by a bitwise-inclusive OR of flags from the following list, defined in <fcntl.h>:

  • AT_REMOVEDIR โ€” Remove the directory entry specified by fd and path as a directory, not a normal file. removes the directory entry from fd and path as a directory, not a normal file ๐ŸŽ€

If unlinkat() is passed the special value AT_FDCWD in the fd parameter, the current working directory shall be used and the behavior shall be identical to a call to unlink() or rmdir() respectively, depending on whether or not the AT_REMOVEDIR bit is set in flag. if fd is AT_FDCWD, it uses the current working directory and acts exactly like unlink() or rmdir(), depending on whether AT_REMOVEDIR is set in flag โœจ


๐Ÿ’– RETURN VALUE ๐Ÿ’–

Upon successful completion, these functions shall return 0. Otherwise, these functions shall return -1 and set errno to indicate the error. If -1 is returned, the named file shall not be changed. so if you see -1, bestie, nothing got unlinked, periodt ๐Ÿ’€


๐Ÿ‘‘ ERRORS ๐Ÿ‘‘

These functions shall fail and shall not unlink the file if:

  • EACCES โ€” search permission is denied for a component of the path prefix, or write permission is denied on the directory containing the directory entry to be removed. so like, you don't have search perms on some part of the path, or you don't have write perms on the directory that holds the entry you're trying to remove ๐Ÿ™…
  • EBUSY โ€” the file named by path cannot be unlinked because it is being used by the system or another process and the implementation considers this an error. busy bestie, the system or another process is using it and the implementation says that's an error ๐Ÿ˜ญ
  • ELOOP โ€” a loop exists in symbolic links encountered during resolution of path. symlink loop during path resolution, we hate to see it ๐Ÿ”
  • ENAMETOOLONG โ€” the length of a component of a pathname is longer than {NAME_MAX}. one pathname component is longer than NAME_MAX, literally too long ๐Ÿ“
  • ENOENT โ€” a component of path does not name an existing file, or path is an empty string. a component of path doesn't exist, or path is just an empty string ๐Ÿซฅ
  • ENOTDIR โ€” a component of the path prefix names an existing file that is neither a directory nor a symbolic link to a directory, or path contains at least one non-<slash> character and ends with one or more trailing <slash> characters and the last pathname component names an existing file that is neither a directory nor a symbolic link to a directory. not a directory situation: either a path prefix component is a non-directory non-symlink-to-directory, or path has non-slash chars and trailing slashes and the last component is a non-directory non-symlink-to-directory ๐Ÿšซ
  • EPERM โ€” the file named by path is a directory, and either the calling process does not have appropriate privileges, or the implementation prohibits using unlink() on directories. path is a directory, and either you don't have the privileges or the implementation just says no unlink() on directories ๐Ÿ”’
  • EPERM or EACCES โ€” the S_ISVTX flag is set on the directory containing the file referred to by path and the process does not satisfy the criteria specified in the Base Definitions volume of POSIX.1โ€2017, Section 4.3, Directory Protection. sticky bit is set on the parent directory and you don't meet the POSIX.1โ€2017 Base Definitions Section 4.3 Directory Protection criteria ๐Ÿ“
  • EROFS โ€” the directory entry to be unlinked is part of a read-only file system. read-only file system, so the entry is stuck there ๐ŸงŠ

The unlinkat() function shall fail if:

  • EACCES โ€” the access mode of the open file description associated with fd is not O_SEARCH and the permissions of the directory underlying fd do not permit directory searches. the fd's open file description access mode isn't O_SEARCH, and the directory under fd doesn't allow directory searches ๐Ÿ”
  • EBADF โ€” path does not specify an absolute path and fd is neither AT_FDCWD nor a valid file descriptor open for reading or searching. path isn't absolute, and fd is neither AT_FDCWD nor a valid fd open for reading or searching ๐Ÿ’€
  • ENOTDIR โ€” path is not an absolute path and fd is a file descriptor associated with a non-directory file. path isn't absolute, and fd is attached to a non-directory file ๐Ÿšช
  • EEXIST or ENOTEMPTY โ€” the flag parameter has the AT_REMOVEDIR bit set and path names a directory that is not empty, or there are hard links to the directory other than dot or a single entry in dot-dot. AT_REMOVEDIR is set, but the directory isn't empty, or it has hard links besides dot or one dot-dot entry ๐Ÿ“
  • ENOTDIR โ€” the flag parameter has the AT_REMOVEDIR bit set and path does not name a directory. AT_REMOVEDIR is set, but path isn't a directory ๐Ÿ™ƒ

These functions may fail and not unlink the file if:

  • EBUSY โ€” the file named by path is a named STREAM. path is a named STREAM, so busy ๐ŸŒŠ
  • ELOOP โ€” more than {SYMLOOP_MAX} symbolic links were encountered during resolution of path. you hit more than SYMLOOP_MAX symlinks while resolving path ๐Ÿ”—
  • ENAMETOOLONG โ€” the length of a pathname exceeds {PATH_MAX}, or pathname resolution of a symbolic link produced an intermediate result with a length that exceeds {PATH_MAX}. pathname length goes over PATH_MAX, or resolving a symlink made an intermediate result longer than PATH_MAX ๐Ÿ“
  • ETXTBSY โ€” the entry to be unlinked is the last directory entry to a pure procedure (shared text) file that is being executed. the entry is the last directory entry to a pure procedure (shared text) file that's currently executing ๐Ÿƒ

The unlinkat() function may fail if:

  • EINVAL โ€” the value of flag is not valid. flag value is invalid โŒ

The following sections are informative. iykyk, informative means it's not normative, but still iconic โœจ


๐Ÿ”ฅ EXAMPLES ๐Ÿ”ฅ

The following example shows how to remove a link to a file named /home/cnd/mod1 by removing the entry named /modules/pass1.

           #include <unistd.h>

           char *path = "/modules/pass1";
           int   status;
           ...
           status = unlink(path);

๐ŸŽ€ Checking for an Error ๐ŸŽ€

The following example fragment creates a temporary password lock file named LOCKFILE, which is defined as /etc/ptmp, and gets a file descriptor for it. If the file cannot be opened for writing, unlink() is used to remove the link between the file descriptor and LOCKFILE.

           #include <sys/types.h>
           #include <stdio.h>
           #include <fcntl.h>
           #include <errno.h>
           #include <unistd.h>
           #include <sys/stat.h>

           #define LOCKFILE "/etc/ptmp"

           int pfd;  /* Integer for file descriptor returned by open call. */
           FILE *fpfd;  /* File pointer for use in putpwent(). */
           ...
           /* Open password Lock file. If it exists, this is an error. */
           if ((pfd = open(LOCKFILE, O_WRONLY| O_CREAT | O_EXCL, S_IRUSR
               | S_IWUSR | S_IRGRP | S_IROTH)) == -1)  {
               fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
               exit(1);
           }

           /* Lock file created; proceed with fdopen of lock file so that
              putpwent() can be used.
            */
           if ((fpfd = fdopen(pfd, "w")) == NULL) {
               close(pfd);
               unlink(LOCKFILE);
               exit(1);
           }

๐Ÿฆ‹ Replacing Files ๐Ÿฆ‹

The following example fragment uses unlink() to discard links to files, so that they can be replaced with new versions of the files. The first call removes the link to LOCKFILE if an error occurs. Successive calls remove the links to SAVEFILE and PASSWDFILE so that new links can be created, then removes the link to LOCKFILE when it is no longer needed.

           #include <sys/types.h>
           #include <stdio.h>
           #include <fcntl.h>
           #include <errno.h>
           #include <unistd.h>
           #include <sys/stat.h>

           #define LOCKFILE "/etc/ptmp"
           #define PASSWDFILE "/etc/passwd"
           #define SAVEFILE "/etc/opasswd"
           ...
           /* If no change was made, assume error and leave passwd unchanged. */
           if (!valid_change) {
               fprintf(stderr, "Could not change password for user %s\n", user);
               unlink(LOCKFILE);
               exit(1);
           }

           /* Change permissions on new password file. */
           chmod(LOCKFILE, S_IRUSR | S_IRGRP | S_IROTH);

           /* Remove saved password file. */
           unlink(SAVEFILE);

           /* Save current password file. */
           link(PASSWDFILE, SAVEFILE);

           /* Remove current password file. */
           unlink(PASSWDFILE);

           /* Save new password file as current password file. */
           link(LOCKFILE,PASSWDFILE);

           /* Remove lock file. */
           unlink(LOCKFILE);

           exit(0);

๐ŸŒˆ APPLICATION USAGE ๐ŸŒˆ

Applications should use rmdir() to remove a directory. so like, if you're trying to remove a directory, use rmdir(), bestie ๐Ÿ’…

๐Ÿ’– RATIONALE (the tea on why it's Like This) ๐Ÿ’–

So why can't just anyone yeet a directory with unlink()? Bestie, in many historical implementations, unlinking a directory is restricted to the superuser โ€” and the reasons are spelled out over in link() (also peep rename() while you're there, they're in the same lore arc). ๐Ÿซถ

Now, the [EBUSY] of it all. In historical implementations, [EBUSY] literally meant mount point busy''</pink>. But since this volume of POSIX.1โ€2017 does **not** cover the system administration concepts of mounting and unmounting, the description of that error got glow-up'd into <pink>resource busy''. (Some device drivers use it that exact way when a second process tries to open an exclusive use device, iykyk.) The wording is also intended to let implementations refuse to remove a directory if it's the root or the current working directory of any process. No cap, that's a real permission slip. ๐Ÿ’…

Then the standard developers reviewed TR 24715โ€2006 and noticed something spicy: LSB-conforming implementations may return [EISDIR] instead of [EPERM] when unlinking a directory. They considered changing the requirement so [EPERM] could be [EPERM] or [EISDIR]... and then decided against it ๐Ÿ˜ญ because it would break existing strictly conforming and conforming applications. So here's your takeaway, bestie: applications written for portability to both POSIX.1โ€2008 and the LSB should be prepared to handle either error code. Both. Handle both. ๐Ÿ‘‘


And now, the moment: why does unlinkat() even exist?? โœจ Because the whole purpose of the unlinkat() function is to remove directory entries in directories other than the current working directory without exposure to race conditions. Here's the problem it solves: any part of the path of a file could be changed in parallel to a call to unlink(), and that results in unspecified behavior ๐Ÿ’€. By opening a file descriptor for the target directory and using the unlinkat() function, it can be guaranteed that the removed directory entry is located relative to the desired directory. Main character energy from a file descriptor, honestly. ๐ŸŒˆ

๐Ÿ”ฎ FUTURE DIRECTIONS ๐Ÿ”ฎ

None.

(Yes queen, nothing. The future is a blank canvas, and this function is not on it. ๐Ÿ’…)

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

Go read these next, they're all in the friend group:

  • close()
  • link()
  • remove()
  • rename()
  • rmdir()
  • symlink()

Also the required reading from the Base Definitions volume of POSIX.1โ€2017, Section 4.3, Directory Protection, plus the headers <fcntl.h> and <unistd.h>. ๐ŸŽ€

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .

okay that's the whole page bestie, you ate it up, every last line ๐Ÿ’–โœจ

This one's brought to you by IEEE/The Open Group, dated 2017, and it lives under the name UNLINK(3P). Slay, go forth and unlink responsibly ๐Ÿฆ‹๐ŸŒธ๐Ÿ’…

๐Ÿ“ฆ where this page comes from