gonohup

nohup return to back to program in 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 ?


Solution

  • 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:

    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
    }