implemented wxSingleInstanceChecker for Unix
[wxWidgets.git] / src / unix / snglinst.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: unix/snglinst.cpp
3 // Purpose: implements wxSingleInstanceChecker class for Unix using
4 // lock files with fcntl(2) or flock(2)
5 // Author: Vadim Zeitlin
6 // Modified by:
7 // Created: 09.06.01
8 // RCS-ID: $Id$
9 // Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10 // License: wxWindows license
11 ///////////////////////////////////////////////////////////////////////////////
12
13 // ============================================================================
14 // declarations
15 // ============================================================================
16
17 // ----------------------------------------------------------------------------
18 // headers
19 // ----------------------------------------------------------------------------
20
21 #ifdef __GNUG__
22 #pragma implementation "snglinst.h"
23 #endif
24
25 // For compilers that support precompilation, includes "wx.h".
26 #include "wx/wxprec.h"
27
28 #ifdef __BORLANDC__
29 #pragma hdrstop
30 #endif
31
32 #if wxUSE_SNGLINST_CHECKER
33
34 #ifndef WX_PRECOMP
35 #include "wx/string.h"
36 #include "wx/log.h"
37 #include "wx/intl.h"
38 #include "wx/file.h"
39 #endif //WX_PRECOMP
40
41 #include "wx/utils.h" // wxGetHomeDir()
42
43 #include "wx/snglinst.h"
44
45 #include <unistd.h>
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <signal.h> // for kill()
49
50 #ifdef HAVE_FCNTL
51 #include <fcntl.h>
52 #elif defined(HAVE_FLOCK)
53 #include <sys/file.h>
54 #else
55 // normally, wxUSE_SNGLINST_CHECKER must have been reset by configure
56 #error "wxSingleInstanceChecker can't be compiled on this platform"
57 #endif // fcntl()/flock()
58
59 // ----------------------------------------------------------------------------
60 // private functions: (exclusively) lock/unlock the file
61 // ----------------------------------------------------------------------------
62
63 enum LockOperation
64 {
65 LOCK,
66 UNLOCK
67 };
68
69 #ifdef HAVE_FCNTL
70
71 static int wxLockFile(int fd, LockOperation lock)
72 {
73 // init the flock parameter struct
74 struct flock fl;
75 fl.l_type = lock == LOCK ? F_WRLCK : F_UNLCK;
76
77 // lock the entire file
78 fl.l_whence =
79 fl.l_start =
80 fl.l_len = 0;
81
82 // is this needed?
83 fl.l_pid = getpid();
84
85 return fcntl(fd, F_SETLK, &fl);
86 }
87
88 #else // HAVE_FLOCK
89
90 static int wxLockFile(int fd, LockOperation lock)
91 {
92 return flock(fd, lock == LOCK ? LOCK_EX | LOCK_NB : LOCK_UN);
93 }
94
95 #endif // fcntl()/flock()
96
97 // ----------------------------------------------------------------------------
98 // wxSingleInstanceCheckerImpl: the real implementation class
99 // ----------------------------------------------------------------------------
100
101 class wxSingleInstanceCheckerImpl
102 {
103 public:
104 wxSingleInstanceCheckerImpl()
105 {
106 m_fdLock = -1;
107 m_pidLocker = 0;
108 }
109
110 bool Create(const wxString& name);
111
112 pid_t GetLockerPID() const { return m_pidLocker; }
113
114 ~wxSingleInstanceCheckerImpl() { Unlock(); }
115
116 private:
117 // try to create and lock the file
118 bool CreateLockFile();
119
120 // unlock and remove the lock file
121 void Unlock();
122
123 // the descriptor of our lock file, -1 if none
124 int m_fdLock;
125
126 // pid of the process owning the lock file
127 pid_t m_pidLocker;
128
129 // the name of the lock file
130 wxString m_nameLock;
131 };
132
133 // ============================================================================
134 // wxSingleInstanceCheckerImpl implementation
135 // ============================================================================
136
137 bool wxSingleInstanceCheckerImpl::CreateLockFile()
138 {
139 // try to open the file
140 m_fdLock = open(m_nameLock,
141 O_WRONLY | O_CREAT | O_EXCL,
142 S_IREAD | S_IWRITE);
143
144 if ( m_fdLock != -1 )
145 {
146 // try to lock it
147 if ( wxLockFile(m_fdLock, LOCK) == 0 )
148 {
149 // fine, we have the exclusive lock to the file, write our PID
150 // into it
151 m_pidLocker = getpid();
152
153 // use char here, not wxChar!
154 char buf[256]; // enough for any PID size
155 int len = sprintf(buf, "%d", m_pidLocker) + 1;
156
157 if ( write(m_fdLock, buf, len) != len )
158 {
159 wxLogSysError(_("Failed to write to lock file '%s'"),
160 m_nameLock.c_str());
161
162 Unlock();
163
164 return FALSE;
165 }
166
167 fsync(m_fdLock);
168
169 return TRUE;
170 }
171
172 // couldn't lock: this might have happened because of a race
173 // condition: maybe another instance opened and locked the file
174 // between our calls to open() and flock()
175 close(m_fdLock);
176 m_fdLock = -1;
177 }
178
179 // we didn't create and lock the file
180 return FALSE;
181 }
182
183 bool wxSingleInstanceCheckerImpl::Create(const wxString& name)
184 {
185 m_nameLock = name;
186
187 if ( CreateLockFile() )
188 {
189 // nothing more to do
190 return TRUE;
191 }
192
193 // try to open the file for reading and get the PID of the process
194 // which has it
195 wxFile file(name, wxFile::read);
196 if ( !file.IsOpened() )
197 {
198 // well, this is really weird - file doesn't exist and we can't
199 // create it
200 //
201 // normally, this just means that we don't have write access to
202 // the directory where we try to create it, so return failure,
203 // even it might also be a rare case of a race condition when
204 // another process managed to open and lock the file and terminate
205 // (erasing it) before we got here, but this should happen so
206 // rarely in practice that we don't care
207 wxLogError(_("Failed to access lock file."));
208
209 return FALSE;
210 }
211
212 char buf[256];
213 off_t count = file.Read(buf, WXSIZEOF(buf));
214 if ( count == wxInvalidOffset )
215 {
216 wxLogError(_("Failed to read PID from lock file."));
217 }
218 else
219 {
220 if ( sscanf(buf, "%d", &m_pidLocker) == 1 )
221 {
222 if ( kill(m_pidLocker, 0) != 0 )
223 {
224 if ( unlink(name) != 0 )
225 {
226 wxLogError(_("Failed to remove stale lock file '%s'."),
227 name.c_str());
228
229 // return TRUE in this case for now...
230 }
231 else
232 {
233 wxLogMessage(_("Deleted stale lock file '%s'."),
234 name.c_str());
235
236 // retry now
237 (void)CreateLockFile();
238 }
239 }
240 //else: the other process is running
241 }
242 else
243 {
244 wxLogWarning(_("Invalid lock file '%s'."));
245 }
246 }
247
248 // return TRUE if we could get the PID of the process owning the lock file
249 // (whether it is still running or not), FALSE otherwise as it is
250 // unexpected
251 return m_pidLocker != 0;
252 }
253
254 void wxSingleInstanceCheckerImpl::Unlock()
255 {
256 if ( m_fdLock != -1 )
257 {
258 if ( unlink(m_nameLock) != 0 )
259 {
260 wxLogSysError(_("Failed to remove lock file '%s'"),
261 m_nameLock.c_str());
262 }
263
264 if ( wxLockFile(m_fdLock, UNLOCK) != 0 )
265 {
266 wxLogSysError(_("Failed to unlock lock file '%s'"),
267 m_nameLock.c_str());
268 }
269
270 if ( close(m_fdLock) != 0 )
271 {
272 wxLogSysError(_("Failed to close lock file '%s'"),
273 m_nameLock.c_str());
274 }
275 }
276
277 m_pidLocker = 0;
278 }
279
280 // ============================================================================
281 // wxSingleInstanceChecker implementation
282 // ============================================================================
283
284 bool wxSingleInstanceChecker::Create(const wxString& name,
285 const wxString& path)
286 {
287 wxASSERT_MSG( !m_impl,
288 _T("calling wxSingleInstanceChecker::Create() twice?") );
289
290 // must have the file name to create a lock file
291 wxASSERT_MSG( !name.empty(), _T("lock file name can't be empty") );
292
293 m_impl = new wxSingleInstanceCheckerImpl;
294
295 wxString fullname = path;
296 if ( fullname.empty() )
297 {
298 fullname << wxGetHomeDir() << _T('/');
299 }
300
301 fullname << name;
302
303 return m_impl->Create(fullname);
304 }
305
306 bool wxSingleInstanceChecker::IsAnotherRunning() const
307 {
308 wxCHECK_MSG( m_impl, FALSE, _T("must call Create() first") );
309
310 // if another instance is running, it must own the lock file - otherwise
311 // we have it and the locker PID is ours one
312 return m_impl->GetLockerPID() != getpid();
313 }
314
315 wxSingleInstanceChecker::~wxSingleInstanceChecker()
316 {
317 delete m_impl;
318 }
319
320 #endif // wxUSE_SNGLINST_CHECKER
321