TTKMusicPlayer  3.7.0.0
TTKMusicPlayer imitates Kugou UI, the music player uses of qmmp core library based on Qt for windows and linux
ttklockedfile_unix.cpp
Go to the documentation of this file.
1 #include <string.h>
2 #include <errno.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 
6 #include "ttklockedfile.h"
7 
8 bool TTKLockedFile::lock(LockMode mode, bool block)
9 {
10  if (!isOpen()) {
11  qWarning("TTKLockedFile::lock(): file is not opened");
12  return false;
13  }
14 
15  if (mode == NoLock)
16  return unlock();
17 
18  if (mode == m_lock_mode)
19  return true;
20 
21  if (m_lock_mode != NoLock)
22  unlock();
23 
24  struct flock fl;
25  fl.l_whence = SEEK_SET;
26  fl.l_start = 0;
27  fl.l_len = 0;
28  fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK;
29  int cmd = block ? F_SETLKW : F_SETLK;
30  int ret = fcntl(handle(), cmd, &fl);
31 
32  if (ret == -1) {
33  if (errno != EINTR && errno != EAGAIN)
34  qWarning("TTKLockedFile::lock(): fcntl: %s", strerror(errno));
35  return false;
36  }
37 
38  m_lock_mode = mode;
39  return true;
40 }
41 
42 bool TTKLockedFile::unlock()
43 {
44  if (!isOpen()) {
45  qWarning("TTKLockedFile::unlock(): file is not opened");
46  return false;
47  }
48 
49  if (!isLocked())
50  return true;
51 
52  struct flock fl;
53  fl.l_whence = SEEK_SET;
54  fl.l_start = 0;
55  fl.l_len = 0;
56  fl.l_type = F_UNLCK;
57  int ret = fcntl(handle(), F_SETLKW, &fl);
58 
59  if (ret == -1) {
60  qWarning("TTKLockedFile::lock(): fcntl: %s", strerror(errno));
61  return false;
62  }
63 
64  m_lock_mode = NoLock;
65  return true;
66 }
67 
68 TTKLockedFile::~TTKLockedFile()
69 {
70  if (isOpen())
71  unlock();
72 }
#define SEEK_SET
Definition: zip.c:88
const char int mode
Definition: ioapi.h:135