duanke9540 2019-01-02 20:50
浏览 170
已采纳

如何向子进程发送信号?

I'm having trouble sending a signal from a parent process and receiving it in the child process.

This is the code for the child process. It exits when it receives SIGINT.

// child.go
func main() {
    stop := make(chan os.Signal, 1)
    signal.Notify(stop, os.Interrupt)
    fmt.Println("started")

    <-stop
    fmt.Println("stopped")
}

This is the parent process. It starts child.go, sends SIGINT, then waits for it to exit.

// main.go
func main() {
    // Start child process
    cmd := exec.Command("go", "run", "child.go")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    err := cmd.Start()
    if err != nil {
        _, _ = fmt.Fprintf(os.Stderr, "Start: " + err.Error())
        return
    }

    // Wait, then send signal
    time.Sleep(time.Millisecond * 500)
    err = cmd.Process.Signal(os.Interrupt)
    if err != nil {
        _, _ = fmt.Fprintf(os.Stderr, "Signal: " + err.Error())
        return
    }

    // Wait for child process to finish
    err = cmd.Wait()
    if err != nil {
        _, _ = fmt.Fprintf(os.Stderr, "Wait: " + err.Error())
    }
    return
}

This code should print started stopped to show that it worked as expected, but it only prints started and hangs at cmd.Wait(), meaning the child process did not receive the signal.

When I run go run child.go it works fine, so I don't think the problem is with that file. I understand that func (*Process) Signal doesn't work on Windows; I am using Linux.

How can I fix the code so that the child process gets the signal sent by the parent process?

  • 写回答

1条回答 默认 最新

  • dongyi4420 2019-01-02 21:52
    关注

    As mentioned by @JimB in the comments section, the go run is your problem.

    go run child.go will compile child and execute it as it's own process. If you run a ps after go run child.go, you will see two processes running.

    The process you are watching and signalling is the go executable, not the child.

    Replace the exec.Command("go", "run", "child.go") with the compiled binary exec.Command("child")and it should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置