问题
I want to create one file from c program and i want use bit long time in my c binary. But i want create file in such way that until my c program finish processing file created and unlock it nobody(may using vim or any other editor) can able to open and read file contents.
Please help me on this thanks in advance.
回答1:
You can define a mandatory file lock on Unix, for this purpose. However, it's necessary to (re-)mount file system, so that it honors mandatory locks.
1 For example to remount the root fs, use (as root):
mount -oremount,mand /
2 Now, let's create our secret file:
echo "big secret" > locked_file
3 We need to set-group-id, and disable group execution privileges on the file:
chmod g+s,g-x locked_file
And our C code to lock that file: (The code will lock the file, and keep it locked for a while, you can try another terminal to read it, the read will be delayed until lock is released)
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main() {
struct flock fl;
int fd;
fl.l_type = F_WRLCK; /* read/write lock */
fl.l_whence = SEEK_SET; /* beginning of file */
fl.l_start = 0; /* offset from l_whence */
fl.l_len = 0; /* length, 0 = to EOF */
fl.l_pid = getpid(); /* PID */
fd = open("locked_file", O_RDWR | O_EXCL); /* not 100% sure if O_EXCL needed */
fcntl(fd, F_SETLKW, &fl); /* set lock */
usleep(10000000);
printf("\n release lock \n");
fl.l_type = F_UNLCK;
fcntl(fd, F_SETLK, &fl); /* unset lock */
}
More info at http://kernel.org/doc/Documentation/filesystems/mandatory-locking.txt
回答2:
Files can be locked by using flock(). Its syntax is
#include <sys/file.h>
#define LOCK_SH 1 /* shared lock */
#define LOCK_EX 2 /* exclusive lock */
#define LOCK_NB 4 /* don't block when locking */
#define LOCK_UN 8 /* unlock */
int flock(int fd, int operation);
First file is opened using fopen() or open(). Then this opened file is locked using flock() as given below
int fd = open("test.txt","r");
int lock = flock(fd, LOCK_SH); // Lock the file . . .
// . . . .
// Locked file in use
// . . . .
int release = flock(fd, LOCK_UN); // Unlock the file . . .
来源:https://stackoverflow.com/questions/13468238/file-locking-in-linux-using-c-program