In Linux, if you need a file descriptor (e.g., to pass to a file-locking primitive), you can use fileno(FILE*)
to retrieve it. After retrieving the file descriptor, you can use it as if it had been returned by open
.
For example, instead of
int fd = open("myfile.txt", flags);
int result = flock(fd, LOCK_SH);
you could equally well do this:
FILE* f = fopen("myfile.txt", "r");
int result = flock(fileno(f)), LOCK_SH);
Note that fileno
is defined in the POSIX standard, but not in C or C++ standards.
As for your second question, the Linux open()
man page has this to say:
The solution for performing atomic file locking using a lockfile is to
create a unique file on the same file system (e.g., incorporating
hostname and pid), use link(2) to make a link to the lockfile. If
link() returns 0, the lock is successful. Otherwise, use stat(2) on
the unique file to check if its link count has increased to 2, in
which case the lock is also successful.