We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Lock kills service on autoreload
the service is running a tornado instance that autoreloads the service if a file in the mycroft-core tree is modified. The service also contains a Lock that ensures only one service instance is loaded. When the service is reloaded the same PID is used and the lock kills it.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mycroft/lock/__init__.py`
Content:
```
1 
2 # Time-stamp: <2017-04-06 15:55:05 dmendyke>   -*- mode: python; -*-
3 
4 # Copyright 2016 Mycroft AI, Inc.
5 #
6 # This file is part of Mycroft Core.
7 #
8 # Mycroft Core is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Mycroft Core is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Mycroft Core.  If not, see <http://www.gnu.org/licenses/>.
20 
21 #
22 # Required Modules
23 from signal import getsignal, signal, SIGKILL, SIGINT, SIGTERM  # signals
24 import os  # Operating System functions
25 
26 
27 #
28 # Written by Daniel Mendyke [dmendyke@jaguarlandrover.com]
29 __author__ = 'dmendyke'
30 
31 
32 #
33 # Wrapper around chain of handler functions for a specific system level signal.
34 # Often used to trap Ctrl-C for specific application purposes.
35 class Signal(object):  # python 3+ class Signal
36 
37     '''
38     Capture and replace a signal handler with a user supplied function.
39     The user supplied function is always called first then the previous
40     handler, if it exists, will be called.  It is possible to chain several
41     signal handlers together by creating multiply instances of objects of
42     this class, providing a  different user functions for each instance.  All
43     provided user functions will be called in LIFO order.
44     '''
45 
46     #
47     # Constructor
48     # Get the previous handler function then set the passed function
49     # as the new handler function for this signal
50 
51     def __init__(self, sig_value, func):
52         '''
53         Create an instance of the signal handler class.
54 
55         sig_value:  The ID value of the signal to be captured.
56         func:  User supplied function that will act as the new signal handler.
57         '''
58         super(Signal, self).__init__()  # python 3+ 'super().__init__()
59         self.__sig_value = sig_value
60         self.__user_func = func  # store user passed function
61         self.__previous_func = getsignal(sig_value)  # get current handler
62         signal(sig_value, self)
63 
64     #
65     # Called to handle the passed signal
66     def __call__(self, signame, sf):
67         '''
68         Allows the instance of this class to be called as a function.
69         When called it runs the user supplied signal handler than
70         checks to see if there is a previously defined handler.  If
71         there is a previously defined handler call it.
72         '''
73         self.__user_func()  # call user function
74         if self.__previous_func:
75             self.__previous_func(signame, sf)
76 
77     #
78     # reset the signal handler
79     def __del__(self):
80         '''
81         Class destructor.  Called during garbage collection.
82         Resets the signal handler to the previous function.
83         '''
84         signal(self.__sig_value, self.__previous_func)
85 
86     # End class Signal
87 
88 
89 # ----------------------------------------------------------------------------
90 # ----------------------------------------------------------------------------
91 
92 
93 #
94 # Create, delete and manipulate a PID file for this service
95 # ------------------------------------------------------------------------------
96 class Lock(object):  # python 3+ 'class Lock'
97 
98     '''
99     Create and maintains the PID lock file for this application process.
100     The PID lock file is located in /tmp/mycroft/*.pid.  If another process
101     of the same type is started, this class will 'attempt' to stop the
102     previously running process and then change the process ID in the lock file.
103     '''
104 
105     #
106     # Class constants
107     DIRECTORY = '/tmp/mycroft'
108     FILE = '/{}.pid'
109 
110     #
111     # Constructor
112     def __init__(self, service):
113         '''
114         Builds the instance of this object.  Holds the lock until the
115         object is garbage collected.
116 
117         service: Text string.  The name of the service application
118         to be locked (ie: skills, voice)
119         '''
120         super(Lock, self).__init__()  # python 3+ 'super().__init__()'
121         self.__pid = os.getpid()  # PID of this application
122         self.path = Lock.DIRECTORY + Lock.FILE.format(service)
123         self.set_handlers()  # set signal handlers
124         self.create()
125 
126     #
127     # Reset the signal handlers to the 'delete' function
128     def set_handlers(self):
129         '''
130         Trap both SIGINT and SIGTERM to gracefully clean up PID files
131         '''
132         self.__handlers = {SIGINT: Signal(SIGINT, self.delete)}
133         self.__handlers = {SIGTERM: Signal(SIGTERM, self.delete)}
134 
135     #
136     # Check to see if the PID already exists
137     #  If it does exits perform several things:
138     #    Stop the current process
139     #    Delete the exiting file
140     def exists(self):
141         '''
142         Check to see if the PID lock file currently exists.  If it does
143         than send a SIGTERM signal to the process defined by the value
144         in the lock file.  Catch the keyboard interrupt exception to
145         prevent propagation if stopped by use of Ctrl-C.
146         '''
147         if not os.path.isfile(self.path):
148             return
149         with open(self.path, 'r') as L:
150             try:
151                 os.kill(int(L.read()), SIGKILL)
152             except Exception as E:
153                 pass
154 
155     #
156     # Create a lock file for this server process
157     def touch(self):
158         '''
159         If needed, create the '/tmp/mycroft' directory than open the
160         lock file for writting and store the current process ID (PID)
161         as text.
162         '''
163         if not os.path.exists(Lock.DIRECTORY):
164             os.makedirs(Lock.DIRECTORY)
165         with open(self.path, 'w') as L:
166             L.write('{}'.format(self.__pid))
167 
168     #
169     # Create the PID file
170     def create(self):
171         '''
172         Checks to see if a lock file for this service already exists,
173         if so have it killed.  In either case write the process ID of
174         the current service process to to the existing or newly created
175         lock file in /tmp/mycroft/
176         '''
177         self.exists()  # check for current running process
178         self.touch()
179 
180     #
181     # Delete the PID file - but only if it has not been overwritten
182     # by a duplicate service application
183     def delete(self, *args):
184         '''
185         If the PID lock file contains the PID of this process delete it.
186 
187         *args: Ignored.  Required as this fuction is called as a signel
188         handler.
189         '''
190         with open(self.path, 'r') as L:
191             if self.__pid == L.read():
192                 os.unlink(self.path)
193 
194     # End class Lock
195
```

Path: `mycroft/messagebus/service/main.py`
Content:
```
1 # Copyright 2016 Mycroft AI, Inc.
2 #
3 # This file is part of Mycroft Core.
4 #
5 # Mycroft Core is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Mycroft Core is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Mycroft Core.  If not, see <http://www.gnu.org/licenses/>.
17 
18 import tornado.ioloop as ioloop
19 import tornado.web as web
20 
21 from mycroft.configuration import ConfigurationManager
22 from mycroft.messagebus.service.ws import WebsocketEventHandler
23 from mycroft.util import validate_param
24 from mycroft.lock import Lock  # creates/supports PID locking file
25 
26 
27 __author__ = 'seanfitz', 'jdorleans'
28 
29 settings = {
30     'debug': True
31 }
32 
33 
34 def main():
35     import tornado.options
36     lock = Lock("service")
37     tornado.options.parse_command_line()
38     config = ConfigurationManager.get().get("websocket")
39 
40     host = config.get("host")
41     port = config.get("port")
42     route = config.get("route")
43     validate_param(host, "websocket.host")
44     validate_param(port, "websocket.port")
45     validate_param(route, "websocket.route")
46 
47     routes = [
48         (route, WebsocketEventHandler)
49     ]
50     application = web.Application(routes, **settings)
51     application.listen(port, host)
52     ioloop.IOLoop.instance().start()
53 
54 
55 if __name__ == "__main__":
56     main()
57
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mycroft/lock/__init__.py b/mycroft/lock/__init__.py
--- a/mycroft/lock/__init__.py
+++ b/mycroft/lock/__init__.py
@@ -187,8 +187,11 @@
         *args: Ignored.  Required as this fuction is called as a signel
         handler.
         '''
-        with open(self.path, 'r') as L:
-            if self.__pid == L.read():
-                os.unlink(self.path)
-
+        try:
+            with open(self.path, 'r') as L:
+                pid = int(L.read())
+                if self.__pid == pid:
+                    os.unlink(self.path)
+        except IOError:
+            pass
     # End class Lock
diff --git a/mycroft/messagebus/service/main.py b/mycroft/messagebus/service/main.py
--- a/mycroft/messagebus/service/main.py
+++ b/mycroft/messagebus/service/main.py
@@ -17,6 +17,7 @@
 
 import tornado.ioloop as ioloop
 import tornado.web as web
+import tornado.autoreload as autoreload
 
 from mycroft.configuration import ConfigurationManager
 from mycroft.messagebus.service.ws import WebsocketEventHandler
@@ -35,6 +36,13 @@
     import tornado.options
     lock = Lock("service")
     tornado.options.parse_command_line()
+
+    def reload_hook():
+        """ Hook to release lock when autoreload is triggered. """
+        lock.delete()
+
+    tornado.autoreload.add_reload_hook(reload_hook)
+
     config = ConfigurationManager.get().get("websocket")
 
     host = config.get("host")

{"golden_diff": "diff --git a/mycroft/lock/__init__.py b/mycroft/lock/__init__.py\n--- a/mycroft/lock/__init__.py\n+++ b/mycroft/lock/__init__.py\n@@ -187,8 +187,11 @@\n         *args: Ignored.  Required as this fuction is called as a signel\n         handler.\n         '''\n-        with open(self.path, 'r') as L:\n-            if self.__pid == L.read():\n-                os.unlink(self.path)\n-\n+        try:\n+            with open(self.path, 'r') as L:\n+                pid = int(L.read())\n+                if self.__pid == pid:\n+                    os.unlink(self.path)\n+        except IOError:\n+            pass\n     # End class Lock\ndiff --git a/mycroft/messagebus/service/main.py b/mycroft/messagebus/service/main.py\n--- a/mycroft/messagebus/service/main.py\n+++ b/mycroft/messagebus/service/main.py\n@@ -17,6 +17,7 @@\n \n import tornado.ioloop as ioloop\n import tornado.web as web\n+import tornado.autoreload as autoreload\n \n from mycroft.configuration import ConfigurationManager\n from mycroft.messagebus.service.ws import WebsocketEventHandler\n@@ -35,6 +36,13 @@\n     import tornado.options\n     lock = Lock(\"service\")\n     tornado.options.parse_command_line()\n+\n+    def reload_hook():\n+        \"\"\" Hook to release lock when autoreload is triggered. \"\"\"\n+        lock.delete()\n+\n+    tornado.autoreload.add_reload_hook(reload_hook)\n+\n     config = ConfigurationManager.get().get(\"websocket\")\n \n     host = config.get(\"host\")\n", "issue": "Lock kills service on autoreload\nthe service is running a tornado instance that autoreloads the service if a file in the mycroft-core tree is modified. The service also contains a Lock that ensures only one service instance is loaded. When the service is reloaded the same PID is used and the lock kills it.\n", "before_files": [{"content": "\n# Time-stamp: <2017-04-06 15:55:05 dmendyke>   -*- mode: python; -*-\n\n# Copyright 2016 Mycroft AI, Inc.\n#\n# This file is part of Mycroft Core.\n#\n# Mycroft Core is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Mycroft Core is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Mycroft Core.  If not, see <http://www.gnu.org/licenses/>.\n\n#\n# Required Modules\nfrom signal import getsignal, signal, SIGKILL, SIGINT, SIGTERM  # signals\nimport os  # Operating System functions\n\n\n#\n# Written by Daniel Mendyke [dmendyke@jaguarlandrover.com]\n__author__ = 'dmendyke'\n\n\n#\n# Wrapper around chain of handler functions for a specific system level signal.\n# Often used to trap Ctrl-C for specific application purposes.\nclass Signal(object):  # python 3+ class Signal\n\n    '''\n    Capture and replace a signal handler with a user supplied function.\n    The user supplied function is always called first then the previous\n    handler, if it exists, will be called.  It is possible to chain several\n    signal handlers together by creating multiply instances of objects of\n    this class, providing a  different user functions for each instance.  All\n    provided user functions will be called in LIFO order.\n    '''\n\n    #\n    # Constructor\n    # Get the previous handler function then set the passed function\n    # as the new handler function for this signal\n\n    def __init__(self, sig_value, func):\n        '''\n        Create an instance of the signal handler class.\n\n        sig_value:  The ID value of the signal to be captured.\n        func:  User supplied function that will act as the new signal handler.\n        '''\n        super(Signal, self).__init__()  # python 3+ 'super().__init__()\n        self.__sig_value = sig_value\n        self.__user_func = func  # store user passed function\n        self.__previous_func = getsignal(sig_value)  # get current handler\n        signal(sig_value, self)\n\n    #\n    # Called to handle the passed signal\n    def __call__(self, signame, sf):\n        '''\n        Allows the instance of this class to be called as a function.\n        When called it runs the user supplied signal handler than\n        checks to see if there is a previously defined handler.  If\n        there is a previously defined handler call it.\n        '''\n        self.__user_func()  # call user function\n        if self.__previous_func:\n            self.__previous_func(signame, sf)\n\n    #\n    # reset the signal handler\n    def __del__(self):\n        '''\n        Class destructor.  Called during garbage collection.\n        Resets the signal handler to the previous function.\n        '''\n        signal(self.__sig_value, self.__previous_func)\n\n    # End class Signal\n\n\n# ----------------------------------------------------------------------------\n# ----------------------------------------------------------------------------\n\n\n#\n# Create, delete and manipulate a PID file for this service\n# ------------------------------------------------------------------------------\nclass Lock(object):  # python 3+ 'class Lock'\n\n    '''\n    Create and maintains the PID lock file for this application process.\n    The PID lock file is located in /tmp/mycroft/*.pid.  If another process\n    of the same type is started, this class will 'attempt' to stop the\n    previously running process and then change the process ID in the lock file.\n    '''\n\n    #\n    # Class constants\n    DIRECTORY = '/tmp/mycroft'\n    FILE = '/{}.pid'\n\n    #\n    # Constructor\n    def __init__(self, service):\n        '''\n        Builds the instance of this object.  Holds the lock until the\n        object is garbage collected.\n\n        service: Text string.  The name of the service application\n        to be locked (ie: skills, voice)\n        '''\n        super(Lock, self).__init__()  # python 3+ 'super().__init__()'\n        self.__pid = os.getpid()  # PID of this application\n        self.path = Lock.DIRECTORY + Lock.FILE.format(service)\n        self.set_handlers()  # set signal handlers\n        self.create()\n\n    #\n    # Reset the signal handlers to the 'delete' function\n    def set_handlers(self):\n        '''\n        Trap both SIGINT and SIGTERM to gracefully clean up PID files\n        '''\n        self.__handlers = {SIGINT: Signal(SIGINT, self.delete)}\n        self.__handlers = {SIGTERM: Signal(SIGTERM, self.delete)}\n\n    #\n    # Check to see if the PID already exists\n    #  If it does exits perform several things:\n    #    Stop the current process\n    #    Delete the exiting file\n    def exists(self):\n        '''\n        Check to see if the PID lock file currently exists.  If it does\n        than send a SIGTERM signal to the process defined by the value\n        in the lock file.  Catch the keyboard interrupt exception to\n        prevent propagation if stopped by use of Ctrl-C.\n        '''\n        if not os.path.isfile(self.path):\n            return\n        with open(self.path, 'r') as L:\n            try:\n                os.kill(int(L.read()), SIGKILL)\n            except Exception as E:\n                pass\n\n    #\n    # Create a lock file for this server process\n    def touch(self):\n        '''\n        If needed, create the '/tmp/mycroft' directory than open the\n        lock file for writting and store the current process ID (PID)\n        as text.\n        '''\n        if not os.path.exists(Lock.DIRECTORY):\n            os.makedirs(Lock.DIRECTORY)\n        with open(self.path, 'w') as L:\n            L.write('{}'.format(self.__pid))\n\n    #\n    # Create the PID file\n    def create(self):\n        '''\n        Checks to see if a lock file for this service already exists,\n        if so have it killed.  In either case write the process ID of\n        the current service process to to the existing or newly created\n        lock file in /tmp/mycroft/\n        '''\n        self.exists()  # check for current running process\n        self.touch()\n\n    #\n    # Delete the PID file - but only if it has not been overwritten\n    # by a duplicate service application\n    def delete(self, *args):\n        '''\n        If the PID lock file contains the PID of this process delete it.\n\n        *args: Ignored.  Required as this fuction is called as a signel\n        handler.\n        '''\n        with open(self.path, 'r') as L:\n            if self.__pid == L.read():\n                os.unlink(self.path)\n\n    # End class Lock\n", "path": "mycroft/lock/__init__.py"}, {"content": "# Copyright 2016 Mycroft AI, Inc.\n#\n# This file is part of Mycroft Core.\n#\n# Mycroft Core is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Mycroft Core is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Mycroft Core.  If not, see <http://www.gnu.org/licenses/>.\n\nimport tornado.ioloop as ioloop\nimport tornado.web as web\n\nfrom mycroft.configuration import ConfigurationManager\nfrom mycroft.messagebus.service.ws import WebsocketEventHandler\nfrom mycroft.util import validate_param\nfrom mycroft.lock import Lock  # creates/supports PID locking file\n\n\n__author__ = 'seanfitz', 'jdorleans'\n\nsettings = {\n    'debug': True\n}\n\n\ndef main():\n    import tornado.options\n    lock = Lock(\"service\")\n    tornado.options.parse_command_line()\n    config = ConfigurationManager.get().get(\"websocket\")\n\n    host = config.get(\"host\")\n    port = config.get(\"port\")\n    route = config.get(\"route\")\n    validate_param(host, \"websocket.host\")\n    validate_param(port, \"websocket.port\")\n    validate_param(route, \"websocket.route\")\n\n    routes = [\n        (route, WebsocketEventHandler)\n    ]\n    application = web.Application(routes, **settings)\n    application.listen(port, host)\n    ioloop.IOLoop.instance().start()\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "mycroft/messagebus/service/main.py"}], "after_files": [{"content": "\n# Time-stamp: <2017-04-06 15:55:05 dmendyke>   -*- mode: python; -*-\n\n# Copyright 2016 Mycroft AI, Inc.\n#\n# This file is part of Mycroft Core.\n#\n# Mycroft Core is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Mycroft Core is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Mycroft Core.  If not, see <http://www.gnu.org/licenses/>.\n\n#\n# Required Modules\nfrom signal import getsignal, signal, SIGKILL, SIGINT, SIGTERM  # signals\nimport os  # Operating System functions\n\n\n#\n# Written by Daniel Mendyke [dmendyke@jaguarlandrover.com]\n__author__ = 'dmendyke'\n\n\n#\n# Wrapper around chain of handler functions for a specific system level signal.\n# Often used to trap Ctrl-C for specific application purposes.\nclass Signal(object):  # python 3+ class Signal\n\n    '''\n    Capture and replace a signal handler with a user supplied function.\n    The user supplied function is always called first then the previous\n    handler, if it exists, will be called.  It is possible to chain several\n    signal handlers together by creating multiply instances of objects of\n    this class, providing a  different user functions for each instance.  All\n    provided user functions will be called in LIFO order.\n    '''\n\n    #\n    # Constructor\n    # Get the previous handler function then set the passed function\n    # as the new handler function for this signal\n\n    def __init__(self, sig_value, func):\n        '''\n        Create an instance of the signal handler class.\n\n        sig_value:  The ID value of the signal to be captured.\n        func:  User supplied function that will act as the new signal handler.\n        '''\n        super(Signal, self).__init__()  # python 3+ 'super().__init__()\n        self.__sig_value = sig_value\n        self.__user_func = func  # store user passed function\n        self.__previous_func = getsignal(sig_value)  # get current handler\n        signal(sig_value, self)\n\n    #\n    # Called to handle the passed signal\n    def __call__(self, signame, sf):\n        '''\n        Allows the instance of this class to be called as a function.\n        When called it runs the user supplied signal handler than\n        checks to see if there is a previously defined handler.  If\n        there is a previously defined handler call it.\n        '''\n        self.__user_func()  # call user function\n        if self.__previous_func:\n            self.__previous_func(signame, sf)\n\n    #\n    # reset the signal handler\n    def __del__(self):\n        '''\n        Class destructor.  Called during garbage collection.\n        Resets the signal handler to the previous function.\n        '''\n        signal(self.__sig_value, self.__previous_func)\n\n    # End class Signal\n\n\n# ----------------------------------------------------------------------------\n# ----------------------------------------------------------------------------\n\n\n#\n# Create, delete and manipulate a PID file for this service\n# ------------------------------------------------------------------------------\nclass Lock(object):  # python 3+ 'class Lock'\n\n    '''\n    Create and maintains the PID lock file for this application process.\n    The PID lock file is located in /tmp/mycroft/*.pid.  If another process\n    of the same type is started, this class will 'attempt' to stop the\n    previously running process and then change the process ID in the lock file.\n    '''\n\n    #\n    # Class constants\n    DIRECTORY = '/tmp/mycroft'\n    FILE = '/{}.pid'\n\n    #\n    # Constructor\n    def __init__(self, service):\n        '''\n        Builds the instance of this object.  Holds the lock until the\n        object is garbage collected.\n\n        service: Text string.  The name of the service application\n        to be locked (ie: skills, voice)\n        '''\n        super(Lock, self).__init__()  # python 3+ 'super().__init__()'\n        self.__pid = os.getpid()  # PID of this application\n        self.path = Lock.DIRECTORY + Lock.FILE.format(service)\n        self.set_handlers()  # set signal handlers\n        self.create()\n\n    #\n    # Reset the signal handlers to the 'delete' function\n    def set_handlers(self):\n        '''\n        Trap both SIGINT and SIGTERM to gracefully clean up PID files\n        '''\n        self.__handlers = {SIGINT: Signal(SIGINT, self.delete)}\n        self.__handlers = {SIGTERM: Signal(SIGTERM, self.delete)}\n\n    #\n    # Check to see if the PID already exists\n    #  If it does exits perform several things:\n    #    Stop the current process\n    #    Delete the exiting file\n    def exists(self):\n        '''\n        Check to see if the PID lock file currently exists.  If it does\n        than send a SIGTERM signal to the process defined by the value\n        in the lock file.  Catch the keyboard interrupt exception to\n        prevent propagation if stopped by use of Ctrl-C.\n        '''\n        if not os.path.isfile(self.path):\n            return\n        with open(self.path, 'r') as L:\n            try:\n                os.kill(int(L.read()), SIGKILL)\n            except Exception as E:\n                pass\n\n    #\n    # Create a lock file for this server process\n    def touch(self):\n        '''\n        If needed, create the '/tmp/mycroft' directory than open the\n        lock file for writting and store the current process ID (PID)\n        as text.\n        '''\n        if not os.path.exists(Lock.DIRECTORY):\n            os.makedirs(Lock.DIRECTORY)\n        with open(self.path, 'w') as L:\n            L.write('{}'.format(self.__pid))\n\n    #\n    # Create the PID file\n    def create(self):\n        '''\n        Checks to see if a lock file for this service already exists,\n        if so have it killed.  In either case write the process ID of\n        the current service process to to the existing or newly created\n        lock file in /tmp/mycroft/\n        '''\n        self.exists()  # check for current running process\n        self.touch()\n\n    #\n    # Delete the PID file - but only if it has not been overwritten\n    # by a duplicate service application\n    def delete(self, *args):\n        '''\n        If the PID lock file contains the PID of this process delete it.\n\n        *args: Ignored.  Required as this fuction is called as a signel\n        handler.\n        '''\n        try:\n            with open(self.path, 'r') as L:\n                pid = int(L.read())\n                if self.__pid == pid:\n                    os.unlink(self.path)\n        except IOError:\n            pass\n    # End class Lock\n", "path": "mycroft/lock/__init__.py"}, {"content": "# Copyright 2016 Mycroft AI, Inc.\n#\n# This file is part of Mycroft Core.\n#\n# Mycroft Core is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Mycroft Core is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Mycroft Core.  If not, see <http://www.gnu.org/licenses/>.\n\nimport tornado.ioloop as ioloop\nimport tornado.web as web\nimport tornado.autoreload as autoreload\n\nfrom mycroft.configuration import ConfigurationManager\nfrom mycroft.messagebus.service.ws import WebsocketEventHandler\nfrom mycroft.util import validate_param\nfrom mycroft.lock import Lock  # creates/supports PID locking file\n\n\n__author__ = 'seanfitz', 'jdorleans'\n\nsettings = {\n    'debug': True\n}\n\n\ndef main():\n    import tornado.options\n    lock = Lock(\"service\")\n    tornado.options.parse_command_line()\n\n    def reload_hook():\n        \"\"\" Hook to release lock when autoreload is triggered. \"\"\"\n        lock.delete()\n\n    tornado.autoreload.add_reload_hook(reload_hook)\n\n    config = ConfigurationManager.get().get(\"websocket\")\n\n    host = config.get(\"host\")\n    port = config.get(\"port\")\n    route = config.get(\"route\")\n    validate_param(host, \"websocket.host\")\n    validate_param(port, \"websocket.port\")\n    validate_param(route, \"websocket.route\")\n\n    routes = [\n        (route, WebsocketEventHandler)\n    ]\n    application = web.Application(routes, **settings)\n    application.listen(port, host)\n    ioloop.IOLoop.instance().start()\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "mycroft/messagebus/service/main.py"}]}