Coverage Report

Created: 2026-02-09 06:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmFileLockUnix.cxx
Line
Count
Source
1
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2
   file LICENSE.rst or https://cmake.org/licensing for details.  */
3
#include <cerrno> // errno
4
#include <cstdio> // SEEK_SET
5
6
#include <fcntl.h>
7
#include <unistd.h>
8
9
#include "cmFileLock.h"
10
#include "cmSystemTools.h"
11
12
134
cmFileLock::cmFileLock() = default;
13
14
cmFileLockResult cmFileLock::Release()
15
134
{
16
134
  if (this->Filename.empty()) {
17
65
    return cmFileLockResult::MakeOk();
18
65
  }
19
69
  int const lockResult = this->LockFile(F_SETLK, F_UNLCK);
20
21
69
  this->Filename = "";
22
23
69
  ::close(this->File);
24
69
  this->File = -1;
25
26
69
  if (lockResult == 0) {
27
69
    return cmFileLockResult::MakeOk();
28
69
  }
29
0
  return cmFileLockResult::MakeSystem();
30
69
}
31
32
cmFileLockResult cmFileLock::OpenFile()
33
134
{
34
134
  this->File = ::open(this->Filename.c_str(), O_RDWR);
35
134
  if (this->File == -1) {
36
65
    return cmFileLockResult::MakeSystem();
37
65
  }
38
69
  return cmFileLockResult::MakeOk();
39
134
}
40
41
cmFileLockResult cmFileLock::LockWithoutTimeout()
42
0
{
43
0
  if (this->LockFile(F_SETLKW, F_WRLCK) == -1) {
44
0
    return cmFileLockResult::MakeSystem();
45
0
  }
46
0
  return cmFileLockResult::MakeOk();
47
0
}
48
49
cmFileLockResult cmFileLock::LockWithTimeout(unsigned long seconds)
50
69
{
51
69
  while (true) {
52
69
    if (this->LockFile(F_SETLK, F_WRLCK) == -1) {
53
0
      if (errno != EACCES && errno != EAGAIN) {
54
0
        return cmFileLockResult::MakeSystem();
55
0
      }
56
69
    } else {
57
69
      return cmFileLockResult::MakeOk();
58
69
    }
59
0
    if (seconds == 0) {
60
0
      return cmFileLockResult::MakeTimeout();
61
0
    }
62
0
    --seconds;
63
0
    cmSystemTools::Delay(1000);
64
0
  }
65
69
}
66
67
int cmFileLock::LockFile(int cmd, int type) const
68
138
{
69
138
  struct ::flock lock;
70
138
  lock.l_start = 0;
71
138
  lock.l_len = 0;                         // lock all bytes
72
138
  lock.l_pid = 0;                         // unused (for F_GETLK only)
73
138
  lock.l_type = static_cast<short>(type); // exclusive lock
74
  lock.l_whence = SEEK_SET;
75
138
  return ::fcntl(this->File, cmd, &lock);
76
138
}