1

The project I'm currently working on works with multiple os.system() calls. I'm working on adding the ability to run these calls in the background. This would start a new thread, call os.system() and redirect all output to /dev/null.

The issue is that I can't think of a best way to end these threads. When I call .join() on a thread running an os.system() call, the system call just takes back over the main thread. I'd like the user to have the ability to terminate these threads.

The solution I've though of was to start one thread, then have that thread start the os.system() call in another thread. The first child thread would continuously check a True/False value. But then I hit the issue of the first child thread terminating the second child thread, so the core issue still remains.

Here is a mock-up of what my code look like now:

import threading
import os

def a():
    os.system('ping www.stackoverflow.com > /dev/null')

threads = []

threads.append(threading.Thread(target=a))
threads[0].start()

#Continue doing other stuff

The problem here is that I cannot come up with a stable way to stop these threads.

The Defalt
  • 69
  • 8
  • http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python This may be of use – Will Apr 22 '16 at 17:04
  • I've already seen that, but the issue is that os.system() thread cannot check a variable since it's occupied with the call. – The Defalt Apr 22 '16 at 17:07
  • Are your threads running `os` methods that will actually run forever, or is `ping` just an example? Also, do you need the threads to stop running for the main thread to continue, or could they just exit when the main thread exits? – Will Apr 22 '16 at 17:14
  • Yes. This project is a manager for a group of network analysis tools. It allows the user select and run tools with a set of commands. Some of these tools do execute infinitely. (Ping is just an example) Yes, I'd like the user to be able to terminate threads when they want. – The Defalt Apr 22 '16 at 17:16

1 Answers1

0

It sounds like you may be able to use daemons, which will stop automatically when all other non-daemon threads shut down.

for job in jobs_to_start:
  threads.append(threading.Thread(target=job))
  threads[-1].setDaemon(True)
  threads[-1].start()

Your main thread was being 'taken over' by the os.system call because thread.join does exactly that: waits until the thread finishes, which yours will not.

If this will not work for you, there is a good answer here, showing how to use subprocess.Popen to make a system call and stop it using terminate.

Community
  • 1
  • 1
Will
  • 4,299
  • 5
  • 32
  • 50