summaryrefslogtreecommitdiff
path: root/src/common/lock.cpp
blob: e21aee5c1f2e8dca808a4050a36a8922ce5ec492 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "lock.hpp"

#include <unistd.h>

#include <cstdio>

#include "../strings/fstring.hpp"
#include "../strings/zstring.hpp"

#include "cxxstdio.hpp"
#include "socket.hpp"

#include "../poison.hpp"

/// number of backups to keep
static
const int backup_count = 10;

/// Protected file writing
/// (Until the file is closed, it keeps the old file)

// Start writing a tmpfile
FILE *lock_fopen(ZString filename, int *info)
{
    FILE *fp;
    int no = getpid();

    // Get a filename that doesn't already exist
    FString newfile;
    do
    {
        newfile = STRPRINTF("%s_%d.tmp", filename, no++);
        fp = fopen(newfile.c_str(), "wx");
    }
    while (!fp);
    *info = --no;
    return fp;
}

// Delete the old file and rename the new file
void lock_fclose(FILE *fp, ZString filename, int *info)
{
    if (fp)
    {
        fclose(fp);
        int n = backup_count;
        FString old_filename = STRPRINTF("%s.%d", filename, n);
        while (--n)
        {
            FString newer_filename = STRPRINTF("%s.%d", filename, n);
            rename(newer_filename.c_str(), old_filename.c_str());
            old_filename = std::move(newer_filename);
        }
        rename(filename.c_str(), old_filename.c_str());

        FString tmpfile = STRPRINTF("%s_%d.tmp", filename, *info);
        rename(tmpfile.c_str(), filename.c_str());
    }
}