doubi12138 2015-11-26 07:10
浏览 118
已采纳

nohup返回golang中的程序

We are trying to excute a nohup script from the golang and here is the command we excute

cmd := exec.Command("nohup","sh",destinationDirPath + "/pf_file_monitor.sh","&>",destinationDirPath + "/nohup.out","&")
_,err = cmd.Output();

The problem is after excuting this command the control is not returing back to the program.

Can anyone please assist me in this ?

  • 写回答

1条回答 默认 最新

  • doudi5524 2015-11-26 07:44
    关注

    So it seems that there are a few things that are tripping out up. I've rewritten the code below, but let me first address each one explicitly so I can explain what I think the confusion is and explain my changes:

    • destinationDirPath + "/pf_file_monitor.sh" - this isn't technically wrong, but it's much more idiomatic (and more reliable) to use filepath.Join; as a general rule, you should never be doing manual string concatenation of paths unless you have a good reason
    • $> - I assume what you're trying to do here is redirect the output of the command to the log file. The issue here is that the symbol $> is only meaningful when you're in a shell (like sh or bash). Go, on the other hand, just sees it as another command line argument, and passes it as an argument to the program. Thus, you're going to have to do this manually. In the example I give below, what I do is open the file up and then set cmd's stdout and stderr pipes (these are io.Writers that control where stdout and stderr go) to the file handle.
    • It won't run in the background. The problem here is that you're using the Run method, which will run the command and block until it finishes. You instead want the Start method, which only starts the command and then immediately returns so your program can keep running.

    Hope this helps! Here's the updated implementation:

    script := filepath.Join(destinationDirPath, "pf_file_monitor.sh")
    log := filepath.Join(destinationDirPath, "nohup.out")
    cmd := exec.Command("nohup", "sh", script)
    
    f, err := os.Create(log)
    if err != nil {
        // handle error
    }
    
    // redirect both stdout and stderr to the log file
    cmd.Stdout = f
    cmd.Stderr = f
    
    // start command (and let it run in the background)
    err = cmd.Start()
    if err != nil {
        // handle error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛