-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path63_execing_processes.go
More file actions
36 lines (31 loc) · 1.26 KB
/
63_execing_processes.go
File metadata and controls
36 lines (31 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package gobyexample
import (
"os"
"os/exec"
"syscall"
)
// ExecingProcessesDemo - in the previous example we looked at spawning external processes.
// We do that when we need an external process accessible to a running Go process. Sometimes
// we just want to completely replace the current Go process with another (perhaps non-Go) one.
// To do this we'll use Go's implementation of the classic `exec` function.
func ExecingProcessesDemo() {
// For our example we'll `exec ls`. Go requires an absolute path to the binary we want to
// execute, so we'll use `exec.LookPath` to find it.
binary, lookErr := exec.LookPath("ls")
if lookErr != nil {
panic(lookErr)
}
// `Exec` requiers arguments in slice form, as opposed to one big string. Note that the first
// argument should be the program name.
args := []string{"ls", "-a", "-l", "-h"}
// `Exec` also needs a set of environment variables to use. Here we just provide our current
// environment.
env := os.Environ()
// Here's the actual `syscall.Exec` call. If this call is successful, the execution of our
// process will end here and be replaced by the process we defined. If there is an error
// we'll get a return value.
execErr := syscall.Exec(binary, args, env)
if execErr != nil {
panic(execErr)
}
}