As long as you don't write(2)
to a file (after the unlocking), it does not matter if you unlock it first or close(2)
it first.
However, close(2)
-ing a file would unlock it (at least if no other process share the same opened file descriptor).
See fcntl(2) which says
As well as being removed by an explicit F_UNLCK, record locks are automatically released when the process terminates or if it closes any file descriptor referring to a file on which locks are held.
addenda: should check for failures
Notice that your code is missing error checking. Almost every library function or syscall, in particular fcntl
, read
, write
, could fail (and set errno
to be displayed by e.g. perror
or strerror(errno)
in some log or print). You don't check the success or failure of fcntl
in your LockFile
or UnlockFile
functions, and you don't check neither in the caller.