Locking files in linux with c/c++
Yes, this is possible.
The Unix way to do this is via fcntl
or lockf
.
Whatever you choose, make sure to use only it and not mix the two. Have a look at this question (with answer) about it: fcntl, lockf, which is better to use for file locking?.
If you can, have a look at section 14.3 in Advanced Programming in the UNIX Environment.
Linux file locking
Using open
and the advisory flock
locking, the writers need to hold a LOCK_EX
exclusive lock. The readers must not hold any lock and they then might see the file being truncated abruptly.
Plain fopen
can be used for readers. For well-behaving writers,
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#include <stdio.h>
// never truncates
int fd = open("foo.log", O_CREAT|O_WRONLY /*or O_RDWR */, 0644 /* mode */);
if (flock(fd, LOCK_EX|LOCK_NB) != 0) {
perror("Locking failed - I am not an exclusive writer");
exit(1);
}
// I hold the exclusive lock - now, truncate the file to 0 bytes
ftruncate(fd, 0);
(other error checking omitted for brevity)
If you wish to use <stdio.h>
routines with the file from thereon, you can use fdopen
:
// "w" will not truncate!
FILE *f = fdopen(fd, "w"); // or `r+` for O_RDWR...
Note that a reader must not set a LOCK_SH
lock on the file, otherwise it cannot be opened by a writer.
lock file on linux and if lock successful become daemon?
Lock files don't require any file locking such as flock
. The existence of the file is used as the lock. Add O_EXCL
to the open
call. If open
succeeds, you have the lock; then to release the lock you remove
or unlink
the file.
You need some handling for stale lock files in the case of a crash. That's one reason they are typically created in a particular directory, because the system startup scripts know about it and delete the lock files.
Related Topics
Three Forward Slashes for Block Commenting
C++ Class or Struct Compatiblity with C Struct
Weak_Ptr, Make_Shared and Memory Deallocation
How to Differentiate (When Overloading) Between Prefix and Postfix Forms of Operator++? (C++)
Random Number Generator - Why Seed Every Time
Why Openmp Under Ubuntu 12.04 Is Slower Than Serial Version
Are Dollar-Signs Allowed in Identifiers in C++03
Can't Access Derived Class Method from Pointer of Type Base Class
How to Make a C++ Console Program Exit
How to Use the Ansi Escape Code for Outputting Colored Text on Console
Why Can't Std::Function Bind to C-Style Variadic Functions
How to Benchmark Boost Spirit Parser
How to Find Substring from String
Visual Studio Debugger Error: Unable to Start Program Specified File Cannot Be Found