文件锁定在C

时间:2018-04-13 15:06:48

标签: c fopen fcntl

我有一个文件,将由多个进程读写。因此,要在我使用fcntl()的多个进程之间同步文件。

假设我们有一个文件orignal.txt,我们在orignal.txt中有一些内容。假设文件中的内容是:

show core status
show table status
show action status

现在假设我们有三个进程A,B,C,可以访问orignal.txt以删除其中的内容。说A将删除show core statusB将删除show table statusC将删除show action status

实际上show core statusshow table statusshow action status是与特定流程相关的一些命令,所以我假设show core statusA相关,所以每当他将会show core status写入文件orignal.txt,在A终止之前,它会从文件show core status中删除orignal.txt。与其他流程相同。 所以为此,我编写了代码。

注意:这是一个常用的API,用于删除文件中的所有三个进程(A,B,C)将使用的内容。

#define ACQUIRE_LOCK 1
#define RELEASE_LOCK 0    
int delete_content_from_file(char *command)
{
    FILE *fp, *tempFd;
    char buf[4096];
    int ret;
    fp = fopen ("orignal.txt", "r+");
    if (fp == NULL)
    {
        printf("orignal.txt does not exist");
        return -1;
    }

    printf("Acquiring lock for orignal.txt");
    ret = fileSync(fp,ACQUIRE_LOCK,F_WRLCK);
    if(ret == -1)
    {
    printf("Failed to acquire lock");
    exit(EXIT_FAILURE);
    }
    tempFd = fopen ("duplicate.txt", "w");
    if (tempFd == NULL)
    {
       printf("Duplicate.txt not exist");
       return -1;
    }

    // read text until newline
    while (!feof(fp))
    {
        if (fgets (buf, sizeof(buf), fp) != NULL)
        {
            buf[strlen(buf)-1]='\0';

            if ((ret = strcmp (command, buf)) != 0) {
            fprintf(tempFd, "%s\n", buf);
        }
    }

fclose(tempFd);
system("cp duplicate.txt orignal.txt");
remove("duplicate.txt");
printf("Releasing lock");
ret = fileSync(fp,RELEASE_LOCK,F_UNLCK);
if(ret == -1)
{
    printf("unable to release the lock for orignal.txt");
    return -1;
}
fclose (fp);
return 0;
}

int fileSync(FILE *fd,bool flag,short lock_type)
{
    struct flock lock;
    lock.l_type = lock_type;
    lock.l_whence = SEEK_SET;   // Starting from the begining of the file
    lock.l_start = 0;  // no offset
    lock.l_len = 0;  // to the end of file. 0 means EOF
    if(flag == ACQUIRE_LOCK)
    {
        if(fcntl(fileno(fd), F_SETLKW, &lock) < 0)
        {
            perror("Error to acquire lock");
            return -1;
        }

    }  
   else
   {
       if(fcntl(fileno(fd), F_UNLCK, &lock) < 0)
       {
           perror("Error releasing lock");
           return -1;
       }

   }
   return 0;
}

我的期望:当A释放锁定时,文件的内容应该成为
show table status
show action status

B将释放锁定时,文件的内容应该变为 show action statusC释放锁时,文件将变为空。

但是

我得到了什么:当A释放锁定时,文件的内容是相同的。所有三条线都存在。但是当B释放锁定时,我看到B已从文件中删除了内容show table status,同一C也删除了show action status

这不是固定行为,有时B不会删除内容,但A会删除或C删除。

我在这一点上受到了打击。在我看来,文件没有在进程之间同步。任何帮助将不胜感激。在此先感谢!

0 个答案:

没有答案