我有一個跟蹤文件更改的程序,應該在文件更改時重新啟動指定的進程。我過去常常cmd.Process.Kill()殺死以前的進程,但它在Kill()調用后仍然存在。一些與流程相關的代碼從項目開始:// ShellPlugin allows to run shell commands in task runner type ShellPlugin struct { scope *scope.Scope params Params log logging.Logger done chan bool}// Call calls a pluginfunc (p *ShellPlugin) Call(tx *job.RunContext, r plugins.JobRunner) (err error) { defer close(p.done) // process: /bin/sh -c ping google.com cmd, err := p.params.createProcess(p.scope) if err != nil { return fmt.Errorf("failed to create process to execute command '%s': %s", p.params.Command, err) } p.log.Debug("command: '%s'", p.params.Command) p.log.Debug(`starting process "%s"...`, strings.Join(cmd.Args, " ")) if err = cmd.Start(); err != nil { return fmt.Errorf(`failed to execute command "%s": %s`, strings.Join(cmd.Args, " "), err) } go func() { select { case <- p.done: p.log.Debug("received stop signal") if err := cmd.Process.Kill(); err != nil { p.log.Warn("kill: %s", err.Error()) } p.log.Debug("Killed") } }() if err := cmd.Wait(); err != nil { return formatExitError(err) } p.log.Debug("done") return nil}// Cancel called when task should be canceledfunc (p *ShellPlugin) Cancel(ctx *job.RunContext) error { p.done <- true return nil}Call()開始工作并Cancel()取消它。兩者都調用了單獨的 goroutine。完整的源代碼在這里
調用 cmd.Process.Kill() 后進程不會終止
慕桂英4014372
2023-06-12 17:03:29