How to achieve desired results when using the subprocees Popen.send_signal(CTRL_C_EVENT) in Windows?

前端 未结 2 1762
[愿得一人]
[愿得一人] 2020-12-28 23:52

In python 2.7 in windows according to the documentation you can send a CTRL_C_EVENT (Python 2.7 Subprocess Popen.send_signal documentation). However when I tried it I did no

相关标签:
2条回答
  • 2020-12-29 00:15

    This method of signal handling by subprocesses worked for me on both Linux and Windows 2008, both using Python 2.7.2, but it uses Ctrl-Break instead of Ctrl-C. See the note about process groups and Ctrl-C in http://msdn.microsoft.com/en-us/library/ms683155%28v=vs.85%29.aspx.

    catcher.py:

    import os
    import signal
    import sys
    import time
    
    def signal_handler(signal, frame):
      print 'catcher: signal %d received!' % signal
      raise Exception('catcher: i am done')
    
    if hasattr(os.sys, 'winver'):
        signal.signal(signal.SIGBREAK, signal_handler)
    else:
        signal.signal(signal.SIGTERM, signal_handler)
    
    print 'catcher: started'
    try:
        while(True):
            print 'catcher: sleeping...'
            time.sleep(1)
    except Exception as ex:
        print ex
        sys.exit(0)
    

    thrower.py:

    import signal
    import subprocess
    import time
    import os
    
    args = [
        'python',
        'catcher.py',
        ]
    print 'thrower: starting catcher'
    if hasattr(os.sys, 'winver'):
        process = subprocess.Popen(args, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
    else:
        process = subprocess.Popen(args)
    
    print 'thrower: waiting a couple of seconds for catcher to start...'
    time.sleep(2)
    print 'thrower: sending signal to catch'
    
    if hasattr(os.sys, 'winver'):
        os.kill(process.pid, signal.CTRL_BREAK_EVENT)
    else:
        process.send_signal(signal.SIGTERM)
    
    print 'thrower: i am done'
    
    0 讨论(0)
  • 2020-12-29 00:28

    try with

    win32api.GenerateConsoleCtrlEvent(CTRL_C_EVENT, pgroupid)
    

    or

    win32api.GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pgroupid)
    

    references:

    http://docs.activestate.com/activepython/2.5/pywin3/win32process_CREATE_NEW_PROCESS_GROUP.html

    http://msdn.microsoft.com/en-us/library/ms683155%28v=vs.85%29.aspx

    read info about dwProcessGroupId, the groupid should be the same of the process id

    0 讨论(0)
提交回复
热议问题