2

I am porting some Linux code to Windows that uses lockf()

static string load_bulletin_from_file(const char* cache_filename)
{
    int fd = open(cache_filename, O_RDWR); // lockf requires O_RDWR
    if (fd == -1) {
        etiLog.level(error) << "TAI-UTC bulletin open cache for reading: " <<
            strerror(errno);
        return "";
    }

    lseek(fd, 0, SEEK_SET);

    vector<char> buf(1024);
    vector<char> new_bulletin_data;

    ssize_t ret = lockf(fd, F_LOCK, 0);
    if (ret == 0) {
        // exclusive lock acquired

        do {
            ret = read(fd, buf.data(), buf.size());

            if (ret == -1) {
                close(fd);
                etiLog.level(error) << "TAI-UTC bulletin read cache: " <<
                        strerror(errno);
                return "";
            }

            copy(buf.data(), buf.data() + ret, back_inserter(new_bulletin_data));
        } while (ret > 0);

        close(fd);

        return string{new_bulletin_data.data(), new_bulletin_data.size()};
    }
    else {
        etiLog.level(error) <<
            "TAI-UTC bulletin acquire cache lock for reading: " <<
            strerror(errno);
        close(fd);
    }
    return "";
}

Since lockf() is a POSIX function, Windows does not have it so I don't really know is there a substitute or how to port this piece of code to Windows.

Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
Hojzerice
  • 35
  • 3
  • Have you looked at Cygwin ? – moi Sep 11 '21 at 11:56
  • yea, but would still rather produce native binaries, since I ported a lot of code already – Hojzerice Sep 11 '21 at 11:59
  • Why would Cygwin not produce native binaries? Its a Windows library. Most POSIX functionality is already there. – moi Sep 11 '21 at 12:00
  • It would be a native binary. It has a third party dependency (i.e., Cygwin), which would have to be installed on all machine the executable is deployed to. – Eljay Sep 11 '21 at 12:39
  • You need to likewise call an OS function, use [`LockFile()`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfile). It needs the native file handle, but you haven't mentioned the CRT you use, `_get_osfhandle()` perhaps. – Hans Passant Sep 11 '21 at 13:33
  • if I am reading this right: https://stackoverflow.com/questions/3989545/how-do-i-get-the-file-handle-from-the-fopen-file-structure, fopen uses CreateFile on MinGW on windows anyway, so it should lock the file by itself right? I realy don't want to rewrite this all to use CreateFile and ReadFile if not needed – Hojzerice Sep 11 '21 at 15:08

0 Answers0