duai0935 2019-05-28 19:30
浏览 24

分离Goroutine进入独立程序

I have a function that plays a sound that I want to continue executing after my main program prints to standard output and exits. My reasoning is that I want the sound to finish playing after the program has exited but I don't want the main program to wait for the sound to finish playing before it exits.

I found a method for executing the sound in an independent process by turning it into an executable named playsound and doing go install. Then in my main program, I call this at the end of main():

func startPlaySound() {
    cmd := exec.Command("playsound")
    cmd.Start()
}

main() {
   // code that prints and exits

   startPlaySound()
}

This works but I would like to be able to play the sound after the main program exits without creating an executable file. I would rather run the equivalent of cmd.Start() on the function containing the code to play the sound.

In other words, I would like it to look something like this:

func playSound() {
    // code that plays the sound
}

func startPlaySound() {
   cmd := CmdFromFunction(playSound)
   cmd.Start()
}

main() {
   // code that prints and exits

   startPlaySound()
}

Does something like CmdFromFunction exist?

Response to Question Feedback

  • This is not a duplicate of How do I fork a go process?. I am not trying to fork the main goroutine. I am trying to detach playSound into a separate process that will continue executing after the main goroutine exits. Both of the answers to that question involve executing an external program, which is exactly what I am trying to avoid.
  • "go routines are not meant to be processes" - I literally turned the code from playSound into an executable called playsound and am now executing it as a process using cmd.Start(). I'm just trying to find a more direct route for doing that than creating an entirely separate executable file.
  • 写回答

1条回答 默认 最新

  • dongqiang4819 2019-05-29 06:30
    关注

    GO routines are not meant to be processes

    This might work. I have done this myself, But you might be restricted to bash shell.

    cmd := exec.Command("bash", "-c", "playsound", "&")
    
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法