我想从 c 程序创建一个文件,我想在我的 c 二进制文件中使用一段时间。但我想以这样的方式创建文件,直到我的 c 程序完成处理文件创建并解锁它,没有人(可能使用 vim 或任何其他编辑器)能够打开和读取文件内容。
请提前帮我解决这个问题。
最佳答案
为此目的,您可以在 Unix 上定义一个强制文件锁。 但是,有必要(重新)挂载文件系统,以便它遵守强制锁。
1 例如重新挂载 root fs,使用(作为 root):
mount -oremount,mand /
2 现在,让我们创建我们的 secret 文件:
echo "big secret" > locked_file
3 我们需要设置-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
关于filelock - 使用 C 程序在 Linux 中锁定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13468238/