How to start a process?

It is normally recommended you don't use os.StartProcess directly. Instead, use os/exec which has a much easier interface. Here is how I would start a java subprocess and wait for it to complete.

http://play.golang.org/p/APlp9KK9wx

package main

import (
    "fmt"
    "log"
    "os/exec"
    "strings"
)

func main() {
    var java = "\\jrex64\\bin\\java.exe"

    var path = []string{
        "jrex64\\lib\\rt.jar",
        "jrex64\\lib\\jfxrt.jar",
        "jrex64\\lib\\resources.jar",
        "jrex64\\lib\\ext\\sunjce_provider.jar",
        "jrex64\\lib\\ext\\zipfs.jar",
        "jrex64\\lib\\ext\\sunmscapi.jar",
        "jrex64\\lib\\ext\\sunec.jar",
        "jrex64\\lib\\ext\\dnsns.jar",
        "jrex64\\lib\\ext\\access-bridge-64.jar",
        "jrex64\\lib\\security\\local_policy.jar",
        "jrex64\\lib\\jce.jar",
        "jrex64\\lib\\jfr.jar",
        "jrex64\\lib\\jsse.jar",
        "jrex64\\lib\\charsets.jar",
        "jrex64\\lib\\",
    }

    pathflag := "-Xbootclasspath:" + strings.Join(path, ";")
    cmd := exec.Command(java, "-verbose", pathflag, "-cp Ganesha_lib\\*", "-jar Ganesha.jar")
    err := cmd.Run()

    if err != nil {
        fmt.Println("an error occurred.\n")
        log.Fatal(err)
    }

}

In case you are curious, the reason you got that panic was that attr is a nil pointer. Instead, you could have done attr := new(os.ProcAttr).


Here:

var attr* os.ProcAttr

proc, err := os.StartProcess(name, args, attr)

The attr variable is nil and when dereferenced in os.StartProcess it causes the error you see.


The previous answers don't actually describe how to use os.StartProcess(). Here's an example:

cmdToRun := "/path/to/someCommand"
args := []string{"someCommand", "arg1"}
procAttr := new(os.ProcAttr)
procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
if process, err := os.StartProcess(cmdToRun, args, procAttr); err != nil {
    fmt.Printf("ERROR Unable to run %s: %s\n", cmdToRun, err.Error())
} else {
    fmt.Printf("%s running as pid %d\n", cmdToRun, process.Pid)
}

Note that it's necessary to initialize the ProcAttr.Files field - if you don't, you may get an index out of bounds error deep in the os package. You can use pipes for the files if you want to provide input or process output from the new process in your own code. You may also want to specify the Dir (starting directory) and Env (environment variables) fields.

Tags:

Go