title: Stop systemd service running a python program
body: <p>I created a service to run a Python program and added some lines of code to create a lock to avoid launching it twice.</p>
  <p>Unfortunately I don't know how to configure the service to stop the running program correctly. When running the stop command it doesn't delete the lock, then I can't start the service anymore. If I execute the program myself via CLI and exit with a Ctrl+C, the lock is deleted.</p>
  <p>I've read the manual about <a href="https://www.freedesktop.org/software/systemd/man/systemd.kill.html" rel="nofollow noreferrer">KillMode</a>, <a href="https://www.freedesktop.org/software/systemd/man/systemd.service.html" rel="nofollow noreferrer">ExecStop</a> and <a href="https://man7.org/linux/man-pages/man7/signal.7.html" rel="nofollow noreferrer">Signal</a>. My understanding is that the default configuration was the one I needed.</p>
  <p>Any help please?</p>
  <p><strong>Main program</strong></p>
  <pre class="lang-py prettyprint-override"><code>if __name__ == '__main__':
  
      #Creating lock to avoid launching program twice
      lock = pathlib.Path(&quot;program.lock&quot;)
  
      if not lock.exists():
  
          lock_acquired_on = datetime.now()
  
          with open('program.lock', 'w') as lock:
              lock.write(f'Lock acquired on {lock_acquired_on}')
              logger.info('Added lock file to avoid running the program twice.')
      
          try:
              while True:
  
                  #Doing stuff here
  
  
          except KeyboardInterrupt:
              close_program() #Close other threads
  
          #Removing the lock file
          os.remove(pathlib.Path(&quot;program.lock&quot;))
  
      else:
          with open('program.lock', 'r') as lock:
              lock_acquisition_time = str(lock.readlines()[0])
              logger.info('Programme Maquette Status is already running.') 
              logger.info(lock_acquisition_time)
  </code></pre>
  <p><strong>Service</strong></p>
  <pre class="lang-sh prettyprint-override"><code>[Unit]
  Description=Programme Maquette IoT End-to-End
  After=multi-user.target
  Conflicts=getty@tty1.service
  
  [Service]
  WorkingDirectory=/home/pi/Documents/ProductionMaquette
  Type=simple
  ExecStart=/usr/local/bin/python3.8 /home/pi/Documents/ProductionMaquette/Lo_main.py
  StandardInput=tty-force
  
  [Install]
  WantedBy=multi-user.target
  </code></pre>