1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/snglinst.cpp
3 // Purpose: implements wxSingleInstanceChecker class for Unix using
4 // lock files with fcntl(2) or flock(2)
5 // Author: Vadim Zeitlin
8 // Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #if wxUSE_SNGLINST_CHECKER
30 #include "wx/string.h"
33 #include "wx/utils.h" // wxGetHomeDir()
38 #include "wx/snglinst.h"
41 #include <sys/types.h>
42 #include <sys/stat.h> // for S_I[RW]USR
43 #include <signal.h> // for kill()
48 #elif defined(HAVE_FLOCK)
51 // normally, wxUSE_SNGLINST_CHECKER must have been reset by configure
52 #error "wxSingleInstanceChecker can't be compiled on this platform"
53 #endif // fcntl()/flock()
55 // ----------------------------------------------------------------------------
57 // ----------------------------------------------------------------------------
59 // argument of wxLockFile()
66 // return value of CreateLockFile()
74 // ----------------------------------------------------------------------------
75 // private functions: (exclusively) lock/unlock the file
76 // ----------------------------------------------------------------------------
80 static int wxLockFile(int fd
, LockOperation lock
)
82 // init the flock parameter struct
84 fl
.l_type
= lock
== LOCK
? F_WRLCK
: F_UNLCK
;
86 // lock the entire file
94 return fcntl(fd
, F_SETLK
, &fl
);
99 static int wxLockFile(int fd
, LockOperation lock
)
101 return flock(fd
, lock
== LOCK
? LOCK_EX
| LOCK_NB
: LOCK_UN
);
104 #endif // fcntl()/flock()
106 // ----------------------------------------------------------------------------
107 // wxSingleInstanceCheckerImpl: the real implementation class
108 // ----------------------------------------------------------------------------
110 class wxSingleInstanceCheckerImpl
113 wxSingleInstanceCheckerImpl()
119 bool Create(const wxString
& name
);
121 pid_t
GetLockerPID() const { return m_pidLocker
; }
123 ~wxSingleInstanceCheckerImpl() { Unlock(); }
126 // try to create and lock the file
127 LockResult
CreateLockFile();
129 // unlock and remove the lock file
132 // the descriptor of our lock file, -1 if none
135 // pid of the process owning the lock file
138 // the name of the lock file
142 // ============================================================================
143 // wxSingleInstanceCheckerImpl implementation
144 // ============================================================================
146 LockResult
wxSingleInstanceCheckerImpl::CreateLockFile()
148 // try to open the file
149 m_fdLock
= open(m_nameLock
.fn_str(),
150 O_WRONLY
| O_CREAT
| O_EXCL
,
153 if ( m_fdLock
!= -1 )
156 if ( wxLockFile(m_fdLock
, LOCK
) == 0 )
158 // fine, we have the exclusive lock to the file, write our PID
160 m_pidLocker
= getpid();
162 // use char here, not wxChar!
163 char buf
[256]; // enough for any PID size
164 int len
= sprintf(buf
, "%d", (int)m_pidLocker
) + 1;
166 if ( write(m_fdLock
, buf
, len
) != len
)
168 wxLogSysError(_("Failed to write to lock file '%s'"),
178 // change file's permission so that only this user can access it:
179 if ( chmod(m_nameLock
.fn_str(), S_IRUSR
| S_IWUSR
) != 0 )
181 wxLogSysError(_("Failed to set permissions on lock file '%s'"),
191 else // failure: see what exactly happened
196 if ( errno
!= EACCES
&& errno
!= EAGAIN
)
198 wxLogSysError(_("Failed to lock the lock file '%s'"),
201 unlink(m_nameLock
.fn_str());
205 //else: couldn't lock because the lock is held by another process:
206 // this might have happened because of a race condition:
207 // maybe another instance opened and locked the file between
208 // our calls to open() and flock(), so don't give an error
212 // we didn't create and lock the file
216 bool wxSingleInstanceCheckerImpl::Create(const wxString
& name
)
220 switch ( CreateLockFile() )
223 // there is a lock file, check below if it is still valid
227 // nothing more to do
235 // Check if the file is owned by current user and has 0600 permissions.
236 // If it doesn't, it's a fake file, possibly meant as a DoS attack, and
237 // so we refuse to touch it:
239 if ( wxStat(name
, &stats
) != 0 )
241 wxLogSysError(_("Failed to inspect the lock file '%s'"), name
.c_str());
244 if ( stats
.st_uid
!= getuid() )
246 wxLogError(_("Lock file '%s' has incorrect owner."), name
.c_str());
249 if ( stats
.st_mode
!= (S_IFREG
| S_IRUSR
| S_IWUSR
) )
251 wxLogError(_("Lock file '%s' has incorrect permissions."), name
.c_str());
255 // try to open the file for reading and get the PID of the process
257 wxFile
file(name
, wxFile::read
);
258 if ( !file
.IsOpened() )
260 // well, this is really weird - file doesn't exist and we can't
263 // normally, this just means that we don't have write access to
264 // the directory where we try to create it, so return failure,
265 // even it might also be a rare case of a race condition when
266 // another process managed to open and lock the file and terminate
267 // (erasing it) before we got here, but this should happen so
268 // rarely in practice that we don't care
269 wxLogError(_("Failed to access lock file."));
275 ssize_t count
= file
.Read(buf
, WXSIZEOF(buf
));
276 if ( count
== wxInvalidOffset
)
278 wxLogError(_("Failed to read PID from lock file."));
282 if ( sscanf(buf
, "%d", (int *)&m_pidLocker
) == 1 )
284 if ( kill(m_pidLocker
, 0) != 0 )
286 if ( unlink(name
.fn_str()) != 0 )
288 wxLogError(_("Failed to remove stale lock file '%s'."),
291 // return true in this case for now...
295 wxLogMessage(_("Deleted stale lock file '%s'."),
299 (void)CreateLockFile();
302 //else: the other process is running
306 wxLogWarning(_("Invalid lock file '%s'."), name
.c_str());
310 // return true if we could get the PID of the process owning the lock file
311 // (whether it is still running or not), FALSE otherwise as it is
313 return m_pidLocker
!= 0;
316 void wxSingleInstanceCheckerImpl::Unlock()
318 if ( m_fdLock
!= -1 )
320 if ( unlink(m_nameLock
.fn_str()) != 0 )
322 wxLogSysError(_("Failed to remove lock file '%s'"),
326 if ( wxLockFile(m_fdLock
, UNLOCK
) != 0 )
328 wxLogSysError(_("Failed to unlock lock file '%s'"),
332 if ( close(m_fdLock
) != 0 )
334 wxLogSysError(_("Failed to close lock file '%s'"),
342 // ============================================================================
343 // wxSingleInstanceChecker implementation
344 // ============================================================================
346 bool wxSingleInstanceChecker::Create(const wxString
& name
,
347 const wxString
& path
)
349 wxASSERT_MSG( !m_impl
,
350 wxT("calling wxSingleInstanceChecker::Create() twice?") );
352 // must have the file name to create a lock file
353 wxASSERT_MSG( !name
.empty(), wxT("lock file name can't be empty") );
355 m_impl
= new wxSingleInstanceCheckerImpl
;
357 wxString fullname
= path
;
358 if ( fullname
.empty() )
360 fullname
= wxGetHomeDir();
363 if ( fullname
.Last() != wxT('/') )
365 fullname
+= wxT('/');
370 return m_impl
->Create(fullname
);
373 bool wxSingleInstanceChecker::DoIsAnotherRunning() const
375 wxCHECK_MSG( m_impl
, false, wxT("must call Create() first") );
377 const pid_t lockerPid
= m_impl
->GetLockerPID();
381 // we failed to open the lock file, return false as we're definitely
382 // not sure that another our process is running and so it's better not
383 // to prevent this one from starting up
387 // if another instance is running, it must own the lock file - otherwise
388 // we have it and the locker PID is ours one
389 return lockerPid
!= getpid();
392 wxSingleInstanceChecker::~wxSingleInstanceChecker()
397 #endif // wxUSE_SNGLINST_CHECKER