doutan1905 2017-10-25 13:41
浏览 96
已采纳

检查exec.Cmd是否已在Go中运行

I'm trying to check if an exec.Cmd is running in these scenarios:

  1. Before I actually started the command
  2. After the command has started, but before it finished
  3. After the command has finished

This will allow me to kill this command if it is running so that I can start it again with different parameters.

A simple use case below:

c := exec.Command("omxplayer", "video.mp4")
s, _ := c.StdinPipe() // use the pipe to send the "q" string to quit omxplayer

log.Printf("Running (false): %v
", checkRunning(c)) // prints false: command has not started yet
c.Start()
log.Printf("Running (true): %v
", checkRunning(c)) // print true: command has started

time.AfterFunc(3*time.Second, func() {
  log.Println("about to quit process...")
  log.Printf("Running (true): %v
", checkRunning(c)) // prints true: command still running at this point
  s.Write([]byte("q"))
})

log.Println("waiting for command to end")
log.Printf("Running (true): %v
", checkRunning(c)) // prints true: command still running at this point
c.Wait()
log.Println("command should have ended by now")
log.Printf("Running (false): %v
", checkRunning(c)) // prints false: command ended at this point

Here's the best that I could come up with:

func checkRunning(cmd *exec.Cmd) bool {
  if cmd == nil || cmd.ProcessState != nil && cmd.ProcessState.Exited() || cmd.Process == nil {
    return false
  }

  return true
}

It works for the use case above, but it seems overly complicated and I'm not sure how reliable it is.

Is there a better way?

  • 写回答

2条回答 默认 最新

  • dongxi9326 2017-10-25 13:43
    关注

    Maybe run synchronously in a goroutine and put the result on a channel you can select on?

    c := exec.Command("omxplayer", "video.mp4")
    // setup pipes and such
    ch := make(chan error)
    go func(){
      ch <- c.Run()
    }()
    select{
      case err := <- ch:
        // done! check error
      case .... //timeouts, ticks or anything else
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号