如何锁定文件以使其他进程无法接收它?

问题描述

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
    struct flock fl;
    fl.l_start = 0;
    fl.l_len = 517; //found the size of the file outside (not best practise,I kNow)
    fl.l_whence = SEEK_SET;
    int fd = open("test",O_RDWR);
    if(fd<0)
        perror("open");
    
    fl.l_type = F_RDLCK;
    fl.l_pid = getpid();
    if(fcntl(fd,F_SETLK,&fl) < 0)
    {
        perror("fcntl"); //geting fcntl: Invalid argument
        exit(1);
    }
    
    if(fl.l_type != F_UNLCK)
    {
        printf("file has been exclusively locked by process:%u\n",fl.l_pid);
        printf("press enter to release the file\n");
        getchar();
        fl.l_type = F_UNLCK; //file released
    }
}

我想锁定一个文件test),该文件包含lorem ipsum(一些随机文本),以便其他进程无法cat对其进行锁定,直到当前进程释放该锁为止。但是传递给fcntl的哪个参数是错误的?

编辑: 在注释之后,我已经初始化了fl变量的某些成员(请参见编辑),尽管可以,但是没有。我仍然可以在另一过程中cat锁定文件test ...为什么,何时将其锁定?

解决方法

文件锁定不是强制性锁定-它是建议性锁定。

这意味着,如果cat之类的程序看不到文件是否被锁定,则其他程序是否将其锁定也没关系-cat仍会读取文件。

除非您使用cat的变体来检查文件锁定,否则您将无法使用文件锁定来停止cat

您能做什么呢?

  1. 重命名文件。
  2. 更改文件权限。
  3. 决定不用担心。

最后一个选项是最简单的-并且可能是最有效的。

某些系统确实支持强制性文件锁定。通常,这是通过将不可执行文件上的SGID位置1来表示的。如果您使用的是这样的系统,则应该可以防止cat处理锁定的文件。