2016-10-18 2 views
1

안녕하세요, 저는 child_process.spwan을 사용하여 Windows에서 python 스크립트를 실행하는 하위 프로세스를 시작합니다. 스크립트는 SIGINT를 청취하여 정상적으로 종료합니다. 그러나 Windows는 신호를 지원하지 않으며 모든 노드가 시뮬레이션을 수행했습니다. 따라서 Windows에서 child_process.kill('SIGINT')은 실제로 무조건 프로세스를 종료합니다 (아무런 정상 종료가 없으며 python의 SIGTERM/SIGINT 핸들러가 호출되지 않음). 또한 ctrl+c 문자를 stdin에 쓰는 것도 작동하지 않습니다.Nodejs : Windows에서 하위 프로세스로 Ctrl + C 보내기

파이썬 API를 살펴볼 때, 나는 CTRL_BREAK_EVENT과 CTRL_C_EVENT를 필요로합니다. 노드에 이와 비슷한 플랫폼 별 API가 있는지 궁금합니다.

관련 게시물이 아닌 작업들 : How to send control C node.js and child_processes sending crtl+c to a node.js spawned childprocess using stdin.write()?

답변

1

당신은 그것의 시간을 중지하고 정상적으로 종료 할 수있는 아이에게 신호를 IPC 메시지를 사용할 수 있습니다. 아래의 방법은 을 사용하여 하위 프로세스 & child_process.send()의 부모로부터 메시지를 수신하여 부모로부터 자식에게 메시지를 보냅니다.

아래 코드는 자식이 멈추거나 끝내기까지 오래 걸리는 경우 종료 시간을 1 분으로 설정합니다.

PY-스크립트 wrapper.js

// Handle messages sent from the Parent 
process.on('message', (msg) => { 
    if (msg.action === 'STOP') { 
    // Execute Graceful Termination code 
    process.exit(0); // Exit Process with no Errors 
    } 
}); 

부모 프로세스

const cp = require('child_process'); 
const py = cp.fork('./py-script-wrapper.js'); 

// On 'SIGINT' 
process.on('SIGINT',() => { 
    // Send a message to the python script 
    py.send({ action: 'STOP' }); 

    // Now that the child process has gracefully terminated 
    // exit parent process without error 
    py.on('exit', (code, signal) => { 
    process.exit(0); 
    }); 

    // If the child took too long to exit 
    // Kill the child, and exit with a failure code 
    setTimeout(60000,() => { 
    py.kill(); 
    process.exit(1); 
    }); 

}); 
+1

감사합니다. 이는 자식 프로세스가 노드 프로세스 일 때 확실히 작동합니다. 하지만 결국에는 파이썬 프로세스를 생성해야한다면 (예 :'spawn ('python', [myscript.py ']'), 어떤 리소스 (예 : 소켓)를 보유하고 있지만 자바 스크립트는 전혀 말할 수 없습니다. 파이썬 proc을 교차 플랫폼 방식으로 IPC합니까? – kenmark

0
당신은 나를 위해 일한 Pyhthon 과정에 표준 입력을 통해 '종료'명령을 보낼 수

. 파이썬에서는 input을 사용하여 stdin에서 읽는 스레드를 만들어야합니다. 일단 반환되면 이벤트 플래그를 설정합니다. 주요 응용 프로그램 루프에서 정기적으로 이벤트가 설정되었는지 확인하고 프로그램을 종료합니다.

파이썬 응용 프로그램 (script.py) :

import threading 
import sys 

def quit_watch(event): 
    input("Type enter to quit") 
    event.set() 

def main(): 
    stop = threading.Event() 
    threading.Thread(target=quit_watch, args=[stop]).start() 

    while True: 
     # do work, regularly check if stop is set 
     if stop.wait(1): 
      print("Stopping application loop") 
      break 

if __name__ == '__main__': 
    main() 
    sys.exit(0) 

Node.js를 응용 프로그램 :

child_process = require('child_process') 
child = child_process.spawn('python.exe', ['script.py']) 
// check if process is still running 
assert(child.kill(0) == true) 
// to terminate gracefully, write newline to stdin 
child.stdin.write('\n') 
// check if process terminated itself 
assert(child.kill(0) == false) 
관련 문제