FLOPEN(3)

πŸ“¦ version 15.1, in freebsd 14.5, freebsd 15.1

πŸ’… FLOPEN(3) β€” bestie's guide to reliably opening and locking a file πŸŽ€

okay so real talk, this page is from the Library Functions Manual, and it's about flopen and flopenat β€” the dynamic duo of "open a file and lock it, no cap". ✨


🌸 LIBRARY 🌸

lives in the System Utilities Library β€” that's libutil, link it with -lutil. 🫢


⭐ SYNOPSIS ⭐

like, here's the whole thing verbatim, don't @ me:

#include <sys/fcntl.h>
#include <libutil.h>

int
flopen(const char *path, int flags);

int
flopen(const char *path, int flags, mode_t mode);

int
flopenat(int fd, const char *path, int flags);

int
flopenat(int fd, const char *path, int flags, mode_t mode);

four whole forms, she's versatile πŸ’…


πŸ’– DESCRIPTION πŸ’–

so flopen() opens or creates a file and grabs an exclusive lock on it. it's basically calling open() with the same params and then flock() with an operation argument of LOCK_EX β€” except flopen() is the main character who actually tries to detect and handle the races that can happen between opening / creating the file and locking it. 😭 iconic behaviour honestly.

which is exactly why it's so good for opening lock files, PID files, spool files, mailboxes and other kinds of files that get used for synchronization between processes. it's giving built-different. πŸ”₯

if flags includes O_NONBLOCK and the file is already locked, flopen() will fail and set errno to EWOULDBLOCK. rude but fair πŸ’€

and just like with open(), the extra mode argument is required if flags includes O_CREAT. no skipping it bestie.

now for flopenat() β€” she's equivalent to flopen() except in the case where the path specifies a relative path. in that case the file to be opened is determined relative to the directory associated with the file descriptor fd instead of the current working directory. πŸ¦‹

and if you pass flopenat() the special value AT_FDCWD in the fd parameter, the current working directory is used and the behavior is identical to a call to flopen(). same energy, same vibes. periodt. πŸ‘‘


🌈 RETURN VALUES 🌈

if it works, flopen() returns a valid file descriptor. if not, it returns -1, and sets errno as described in flock(2) and open(2). simple as that. πŸ€·β€β™€οΈ


πŸŽ€ SEE ALSO πŸŽ€

go read those too iykyk πŸ“š


πŸ‘‘ AUTHORS πŸ‘‘

the flopen function and this manual page were written by Dag-Erling Smørgrav <des@FreeBSD.org>. shoutout to the icon who made it all happen 🫢✨


and that's the whole page bestie!! footer tea: this is the Debian version, dated July 28, 2017, and it's FLOPEN(3) β€” so if you see that in a man page footer you'll know exactly what's up πŸ’œπŸ§šβ€β™€οΈ

πŸ“¦ where this page comes from