How to kill subprocess on terminating main process in Go language

huangapple go评论66阅读模式
英文:

How to kill subprocess on terminating main process in Go language

问题

当主进程终止时,我想要终止子进程。

我使用exec.Command()来运行子进程。

然而,主进程可能因为意外错误而被终止,所以我想确保子进程也被终止。

在Go语言中如何实现这一点?

英文:

I want to kill subprocesses when main process is terminating.

I am running the subprocess with exec.Command()

However the main process can be terminated by an unexpected error so I want to be sure the subprocess also be terminated too.

How to archive it in Go language?

答案1

得分: 2

你可能想要使用CommandContext来代替,当主进程被终止时取消上下文。以下是两个示例:第一个示例演示了在短时间超时后终止进程,第二个示例演示了在进程捕获到来自操作系统的外部终止信号时终止子进程:

package main

import (
	"context"
	"os/exec"
	"time"
)

func main() {
	// 基于时间持续时间终止命令
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()

	if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
		// 这将在100毫秒后失败。5秒的休眠将被中断。
	}

	// 或者使用操作系统信号来取消上下文
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
}
英文:

You might want to use CommandContext instead, and cancel the context when your main process is being terminated. Below are two examples: the first one is for a simple demonstration of terminating a process after a short timeout, the second is for terminating a sub-process when your process catches external termination signal from the OS:

package main

import (
	"context"
	"os/exec"
	"time"
)

func main() {
	// terminate the command based on time.Duration
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()

	if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
		// This will fail after 100 milliseconds. The 5 second sleep
		// will be interrupted.
	}

	// or use os signals to cancel the context
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
}

huangapple
  • 本文由 发表于 2023年3月8日 16:11:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定