File locking in Linux using C program

filelock

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.

Best Answer

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

Related Topic