Starting an External Command or Program

This lesson provides an explanation about how to restart a program externally in case of a panic.

The os package contains the function StartProcess to call or start external OS commands or binary executables; its 1st argument is the process to be executed, the 2nd can be used to pass some options or arguments, and the 3rd is a struct that contains basic info about the OS-environment. It returns a pointer to the started process, or an error if it failed.

The exec package contains the structures and functions to accomplish the same task more easily; most important are exec.Command(name string, arg ...string) and Run(). The function exec.Command(name string, arg ...string) needs the name of an OS command or executable and creates a Command object, which can then be executed with Run() which uses this object as its receiver. The following program (which only works under Linux because Linux commands are executed) illustrates their use:

Get hands-on with 1400+ tech skills courses.