Python ignores SIGINT in multithreaded programs - how to fix it?

I have Python 2.6 on MacOS X and multi-threaded operation. The following test code works fine and disables the application on Ctrl-C:

import threading, time, os, sys, signal
def SigIntHandler( signum, frame ) :
  sys.exit( 0 )
signal.signal( signal.SIGINT, SigIntHandler )
class WorkThread( threading.Thread ) :
  def run( self ) :
    while True :
      time.sleep( 1 )
thread = WorkThread()
thread.start()
time.sleep( 1000 )

But if I changed only one line, adding some real work to the workflow, the application will never end Ctrl-C:

import threading, time, os, sys, signal
def SigIntHandler( signum, frame ) :
  sys.exit( 0 )
signal.signal( signal.SIGINT, SigIntHandler )
class WorkThread( threading.Thread ) :
  def run( self ) :
    while True :
      os.system( "svn up" ) # This is really slow and can fail.
      time.sleep( 1 )
thread = WorkThread()
thread.start()
time.sleep( 1000 )

Can this be fixed, or is python not intended for use with threads?

+3
source share
3 answers

A few things that can cause problems:

  • Ctrl-C may fall for svnthat, which ignores it.
  • , -, . , - . , , join() - . Linux, MacOS X .

Python : -)

:. subprocess, , stdin subprocess.PIPE.

+2

Threads Python, .

1) os.system() . . http://docs.python.org/release/2.6.6/library/os.html?highlight=os.system#os.system

2) threading, , , , thread, , thread.exit(). threading docs , , ,

"… the entire Python program exits when only daemon threads are left."

, , , , , , ctrl-c, ( , , ctrl-c), , , subprocess, svn up, .

+2

You probably don't need threads.

Try using the Python module subprocessor even Twisted process support .

+2
source

Source: https://habr.com/ru/post/1771454/


All Articles