~feng-kylin/youker-assistant/youker-assistant

« back to all changes in this revision

Viewing changes to backends/kylin-assistant-daemon/src/single.py

  • Committer: lixiang
  • Date: 2018-03-06 03:13:06 UTC
  • Revision ID: lixiang@kylinos.cn-20180306031306-fd7qnru3vm4a1xjd
Rewrite with Qt5, and add system monitor

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python3
 
2
# -*- coding: utf-8 -*-
 
3
 
 
4
import os, sys, shutil, tempfile
 
5
import subprocess
 
6
 
 
7
# ensure that single instance of applet is running for each user
 
8
class SingleInstance(object):
 
9
 
 
10
    #Initialize, specifying a path to store pids
 
11
    def __init__(self,pidPath):
 
12
 
 
13
        self.pidPath = pidPath
 
14
        self.lasterror = False
 
15
        if os.path.exists(pidPath):
 
16
            # Make sure it is not a "stale" pidFile
 
17
            pid = open(pidPath, 'r').read().strip()
 
18
            # Check list of running pids, if not running it is stale so overwrite
 
19
            pidRunning = subprocess.getoutput('ls -1 /proc | grep ^%s$' % pid)
 
20
            self.lasterror = True if pidRunning else False
 
21
        else:
 
22
            self.lasterror = False
 
23
 
 
24
        if not self.lasterror:
 
25
            # Create a temp file, copy it to pidPath and remove temporary file
 
26
            (fp, temp_path) = tempfile.mkstemp()
 
27
            try:
 
28
                os.fdopen(fp, "w+b").write(bytes(os.getpid()))
 
29
                shutil.copy(temp_path, pidPath)
 
30
                os.unlink(temp_path)
 
31
            except Exception as e:
 
32
                print(str(e))
 
33
 
 
34
    def is_already_running(self):
 
35
         return self.lasterror
 
36
 
 
37
    def __del__(self):
 
38
         if not self.lasterror and os.path.exists(self.pidPath):
 
39
            os.unlink(self.pidPath)