Skip to content

Commit

Permalink
[Windows] Have a single instance of Agent Manager
Browse files Browse the repository at this point in the history
Etienne LAFARGE committed Sep 16, 2015
1 parent 279dabb commit c2f3031
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions win32/gui.py
Original file line number Diff line number Diff line change
@@ -92,8 +92,16 @@
# Windows management
# Import Windows stuff only on Windows
if Platform.is_windows():
import win32api
import win32con
import win32process
import win32serviceutil
import win32service

# project
from utils.pidfile import PidFile
from utils.process import pid_exists

WIN_STATUS_TO_AGENT = {
win32service.SERVICE_RUNNING: AGENT_RUNNING,
win32service.SERVICE_START_PENDING: AGENT_START_PENDING,
@@ -791,7 +799,53 @@ def info_popup(message, parent=None):
QMessageBox.information(parent, 'Message', message, QMessageBox.Ok)


def kill_old_process():
""" Kills or brings to the foreground (if possible) any other instance of this program. It
avoids multiple icons in the Tray on Windows. On OSX, we don't have to do anything: icons
don't get duplicated. """
# On Windows, if a window is already opened, let's just bring it on the foreground
if Platform.is_windows():
# Is there another Agent Manager process running ?
pidfile = PidFile('agent-manager-gui').get_path()

old_pid = None
try:
pf = file(pidfile, 'r')
old_pid = int(pf.read().strip())
pf.close()
except IOError:
pass
except ValueError:
pass

if old_pid is not None and pid_exists(old_pid):
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, old_pid)
exe_path = win32process.GetModuleFileNameEx(handle, 0)

# If (and only if) this process is indeed an instance of the GUI, let's kill it
if 'agent-manager.exe' in exe_path:
win32api.TerminateProcess(handle, -1)

win32api.CloseHandle(handle)

# If we reached that point it means the current process should be the only running
# agent-manager.exe, let's save its pid
pid = str(os.getpid())
try:
fp = open(pidfile, 'w+')
fp.write(str(pid))
fp.close()
except Exception, e:
msg = "Unable to write pidfile: %s" % pidfile
log.exception(msg)
sys.stderr.write(msg + "\n")
sys.exit(1)


if __name__ == '__main__':
# Let's kill any other running instance of our GUI/SystemTray before starting a new one.
kill_old_process()

app = QApplication([])
if Platform.is_mac():
add_image_path(osp.join(os.getcwd(), 'images'))

0 comments on commit c2f3031

Please sign in to comment.