Ljubisa Gavrilovic (Traserman International Ltd) wrote:
> I'm following this list for about a year, so i have checked previous
> messages in order to find an answer. Probably I'm missing some concept...
>
> 1. What I'm interested in is this: I'd like to perform exclusive lock on a
> local file for a short time (open,wait to lock file,read,update,close; or
> whatever is the technique). This file will be used by different running
> instances of the same program (therefore there is not a question about what
> others use for locking (like mailproc etc..))
If you don't have to adopt any particular convention, and you don't
need to lock the same file from multiple hosts via NFS, use flock()
(or similar).
Kernel locks have the advantage that they will always be removed when
the program terminates, regardless of how the the program terminates,
whilst lock files may be left behind if the program terminates
prematurely (e.g. due to an uncaught signal).
Also, kernel locks apply to the actual file (inode), rather than to a
particular filename. Lock files apply to a filename, so they don't
handle the case where a file has multiple names (via symlinks or hard
links).
> Can you help me with giving me a clue how to use such functions. e.g. open
> a file then to make a lock or create a lockfile and then ??? associate with
> opened file??
/* lock a file */
/* if the file is already locked, wait for it to be unlocked */
void lock_file(int fd)
{
if (flock(fd, LOCK_EX) < 0)
{
/* in theory, this should never happen */
perror("lock_file");
exit(1);
}
}
/* unlock a file */
void unlock_file(int fd)
{
if (flock(fd, LOCK_UN) < 0)
{
/* in theory, this should never happen */
perror("unlock_file");
exit(1);
}
}
--
Glynn Clements <[EMAIL PROTECTED]>