dqx36753 2019-01-21 11:49
浏览 769

通过golang程序开始杀死进程

I have a daemon process running and that starts another process. To simulate it right now I have just put 'sleep'. If I kill the process, it remains as zombie. How to clean it properly.

cmd := exec.Command("sleep", "500")
err := cmd.Start()
if err != nil {
    log.Fatal(err)
}
if err := cmd.Process.Kill(); err != nil {
    log.Fatal("failed to kill process: ", err)
}
time.Sleep(10000000 * time.Millisecond)

$ ps aux | grep sleep

37342 0.0 0.0 4276984 1040 s000 S+ 5:09PM 0:00.00 grep sleep

37309 0.0 0.0 0 0 ?? Z 5:09PM 0:00.00 (sleep)

  • 写回答

1条回答 默认 最新

  • dongxibo2095 2019-01-21 12:04
    关注

    You need to cmd.Wait() for it to finish. (In Unix in general, you need to wait(2) to avoid leaking zombies.)

    "os/exec" doesn't have a non-blocking variant of this (there's no equivalent to waitpid(2)) but you can wait in a goroutine:

    // Start the subprocess
    cmd := exec.Command("sleep", "500")
    err := cmd.Start()
    if err != nil {
            log.Fatal(err)
    }
    
    // Wait for it to finish
    done := make(chan struct{})
    go (func () {
            cmd.Wait()
            close(done)
    })()
    
    // Set a timeout
    timeout := time.NewTimer(5 * time.Second)
    
    select {
    case <-done:
            fmt.Println("process completed")
            if !timeout.Stop() {
                    <-timeout.C
            }
    case <-timeout.C:
            fmt.Println("deadline ran out, killing process")
            if err := cmd.Process.Kill(); err != nil {
                    log.Fatal("failed to kill process: ", err)
            }
            <-done
    }
    

    Only one branch of the select will fire, and each does the cleanup necessary for the other one. In the timeout case, after the process is killed, Wait() should return immediately, which should signal the "done" channel.

    评论

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂