new home directory
[feisty_meow.git] / nucleus / library / application / singleton_application.cpp
1 /*****************************************************************************\
2 *                                                                             *
3 *  Name   : singleton_application                                             *
4 *  Author : Chris Koeritz                                                     *
5 *                                                                             *
6 *******************************************************************************
7 * Copyright (c) 2006-$now By Author.  This program is free software; you can  *
8 * redistribute it and/or modify it under the terms of the GNU General Public  *
9 * License as published by the Free Software Foundation; either version 2 of   *
10 * the License or (at your option) any later version.  This is online at:      *
11 *     http://www.fsf.org/copyleft/gpl.html                                    *
12 * Please send any updates to: fred@gruntose.com                               *
13 \*****************************************************************************/
14
15 #include "singleton_application.h"
16
17 #include <basis/functions.h>
18 #include <filesystem/filename.h>
19
20 using namespace basis;
21 using namespace filesystem;
22 using namespace processes;
23
24 namespace application {
25
26 singleton_application::singleton_application(const astring &application_name,
27     const astring &user_name)
28 : c_initial_try(0),
29   _app_lock(new rendezvous(filename(application_name).basename().raw()
30       + "__" + user_name)),
31   _got_lock(false)
32 {
33 }
34
35 singleton_application::~singleton_application()
36 {
37   release_lock();
38   WHACK(_app_lock);
39 }
40
41 bool singleton_application::already_running()
42 { return !allow_this_instance(); }
43
44 bool singleton_application::already_tried() const
45 { return c_initial_try > 0; }
46
47 void singleton_application::release_lock()
48 {
49   if (_got_lock) {
50     _app_lock->unlock();
51     _got_lock = false;
52   }
53 }
54
55 bool singleton_application::allow_this_instance()
56 {
57   if (_got_lock) return true;  // already grabbed it.
58
59   if (!already_tried()) {
60     _got_lock = _app_lock->lock(rendezvous::IMMEDIATE_RETURN);
61     if (_got_lock) c_initial_try = 1;  // succeeded in locking.
62     else c_initial_try = 2;  // failure.
63   }
64
65   return _got_lock;
66 }
67
68 } //namespace.
69