如何从Node正确终止Go进程

问题描述:

I want to build a Grunt task that spawns a Go server and then kills and respawns it when the Go source files change.

I am spawning the Go process like this:

goProcess = child_process.exec('go run main.go', ...

Later I'm trying to kill the process like this:

if (goProcess) {
    goProcess.kill('SIGINT');
}

But the Go process doesn't die.

How can I properly kill the Go process within Node?

I have a working example here https://github.com/sporto/go-must-die

我想构建一个Grunt任务,该任务生成Go服务器,然后在Go源文件更改时杀死并重新生成它 p>

我正在生成如下所示的Go进程: p>

  goProcess = child_process.exec('go run main.go',。  .. 
  code>  pre> 
 
 

稍后,我正在尝试终止该过程: p>

  if(goProcess){  
 goProcess.kill('SIGINT'); 
} 
  code>  pre> 
 
 

但是Go进程不会死。 p>

如何正确终止Node中的Go进程? p>

我在这里有一个有效的示例 https://github.com/sporto/go-must-die p> div>

child_process.exec runs the command in a shell and seems to be returning the PID of the shell process. Use spawn instead.

go run creates an executable and runs it with a different PID. Try building a binary with go build main.go and running the binary from node.js.

goProcess = child_process.spawn('./main')