Kill process when task is aborted

This commit is contained in:
Kevin Sawicki
2013-03-28 22:51:47 -04:00
parent 95218ca9f5
commit 5f9c643ae9
2 changed files with 20 additions and 6 deletions

View File

@@ -30,8 +30,11 @@ class LoadPathsTask
stdout = (data) ->
paths = paths.concat(_.compact(data.split("\n")))
new BufferedProcess({command, args, stdout, exit})
@process = new BufferedProcess({command, args, stdout, exit})
deferred
abort: ->
@aborted = true
if @process?
@process.kill()
@process = null

View File

@@ -2,32 +2,36 @@ ChildProcess = require 'child_process'
module.exports =
class BufferedProcess
process: null
killed: false
constructor: ({command, args, options, stdout, stderr, exit}={}) ->
process = ChildProcess.spawn(command, args, options)
@process = ChildProcess.spawn(command, args, options)
stdoutClosed = true
stderrClosed = true
processExited = true
exitCode = 0
triggerExitCallback = ->
return if @killed
if stdoutClosed and stderrClosed and processExited
exit?(exitCode)
if stdout
stdoutClosed = false
@bufferStream process.stdout, stdout, ->
@bufferStream @process.stdout, stdout, ->
stdoutClosed = true
triggerExitCallback()
if stderr
stderrClosed = false
@bufferStream process.stderr, stderr, ->
@bufferStream @process.stderr, stderr, ->
stderrClosed = true
triggerExitCallback()
if exit
processExited = false
process.on 'exit', (code) ->
@process.on 'exit', (code) ->
exitCode = code
processExited = true
triggerExitCallback()
@@ -36,7 +40,8 @@ class BufferedProcess
stream.setEncoding('utf8')
buffered = ''
stream.on 'data', (data) ->
stream.on 'data', (data) =>
return if @killed
buffered += data
lastNewlineIndex = buffered.lastIndexOf('\n')
if lastNewlineIndex isnt -1
@@ -44,5 +49,11 @@ class BufferedProcess
buffered = buffered.substring(lastNewlineIndex + 1)
stream.on 'close', =>
return if @killed
onLines(buffered) if buffered.length > 0
onDone()
kill: ->
@killed = true
@process.kill()
@process = null