使用C程序在Linux中锁定文件

时间:2012-11-20 07:14:14

标签: filelock

我想从c程序创建一个文件,我想在我的c二进制文件中使用很长时间。但我希望以这样的方式创建文件,直到我的c程序完成处理文件创建并解锁它无人(可能使用vim或任何其他编辑器)能够打开和读取文件内容。

请提前帮助我。

2 个答案:

答案 0 :(得分:4)

为此,您可以在Unix上定义强制文件锁。 但是,有必要(重新)挂载文件系统,以便它遵守强制锁定。

1例如,要重新安装根fs,请使用(以root身份):

mount -oremount,mand /

2现在,让我们创建我们的秘密文件:

echo "big secret" > locked_file

3我们需要set-group-id,并禁用文件的组执行权限:

chmod g+s,g-x locked_file

我们的C代码锁定该文件: (代码将锁定文件,并将其保持锁定一段时间,您可以尝试另一个终端读取它,读取将被延迟,直到锁定被释放)

#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 */

}

更多信息 http://kernel.org/doc/Documentation/filesystems/mandatory-locking.txt

答案 1 :(得分:1)

可以使用flock()锁定文件。它的语法是

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 . . .

使用fopen()或open()打开第一个文件。然后使用flock()锁定这个打开的文件,如下所示

open