Skip to content
API Documentation
BastionGuard™
AppLock.vala
Go to the documentation of this file.
1/*
2 * AppLock.vala
3 *
4 * Copyright 2012-2018 Tony George <teejeetech@gmail.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 * MA 02110-1301, USA.
20 *
21 *
22 */
23
24using TeeJee.Logging;
27using TeeJee.Misc;
28
29public class AppLock : GLib.Object {
30 public string lock_file = "";
31 public string lock_message = "";
32
33 public bool create(string app_name, string message){
34
35 var lock_dir = "/var/run/lock/%s".printf(app_name);
36 dir_create(lock_dir);
37 lock_file = path_combine(lock_dir, "lock");
38
39 try{
40 var file = File.new_for_path(lock_file);
41 if (file.query_exists()) {
42
43 string txt = file_read(lock_file);
44 string process_id = txt.split(";")[0].strip();
45 lock_message = txt.split(";")[1].strip();
46 long pid = long.parse(process_id);
47
48 if (get_process_exe_name(pid).contains("bastionguard-backup")){
49 log_msg(_("Another instance of this application is running")
50 + " (PID=%ld)".printf(pid));
51 return false;
52 }
53 else{
54 log_msg(_("[Warning] Deleted invalid lock"));
55 file.delete();
56 write_lock_file(message);
57 return true;
58 }
59 }
60 else{
61 write_lock_file(message);
62 return true;
63 }
64 }
65 catch (Error e) {
66 log_error (e.message);
67 return false;
68 }
69 }
70
71 private void write_lock_file(string message){
72 string current_pid = ((long) Posix.getpid()).to_string();
73 file_write(lock_file, "%s;%s".printf(current_pid, message));
74 }
75
76 public void remove(){
77 try{
78 var file = File.new_for_path (lock_file);
79 if (file.query_exists()) {
80 file.delete();
81 }
82 }
83 catch (Error e) {
84 log_error (e.message);
85 }
86 }
87
88}
#define _(s)
bool create(string app_name, string message)
Definition AppLock.vala:33
void write_lock_file(string message)
Definition AppLock.vala:71
string lock_file
Definition AppLock.vala:30
string lock_message
Definition AppLock.vala:31
string? file_read(string file_path)
bool file_write(string file_path, string contents)
string path_combine(string path1, string path2)
bool dir_create(string dir_path, bool show_message=false)
void log_error(string message, bool highlight=false, bool is_warning=false)
void log_msg(string message, bool highlight=false)
string get_process_exe_name(long pid=-1)