Skip to main content
Version: 2.10.x(Latest)

Execute Shell Commands​

package main

import (
"fmt"

"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gproc"
)

func main() {
r, err := gproc.ShellExec(gctx.New(), `sleep 3; echo "hello gf!";`)
fmt.Println("result:", r)
fmt.Println(err)
}

After execution, you can see that the program waits for 3 seconds, and the output result is:

result: hello gf!

<nil>

Main Process and Subprocess​

Processes created by the gproc.Manager object are marked as subprocesses by default. In a subprocess program, you can use the gproc.IsChild() method to determine if it is a subprocess.

package main

import (
"os"
"time"

"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gproc"
)

func main() {
var ctx = gctx.New()
if gproc.IsChild() {
g.Log().Printf(ctx, "%d: Hi, I am child, waiting 3 seconds to die", gproc.Pid())
time.Sleep(time.Second)
g.Log().Printf(ctx, "%d: 1", gproc.Pid())
time.Sleep(time.Second)
g.Log().Printf(ctx, "%d: 2", gproc.Pid())
time.Sleep(time.Second)
g.Log().Printf(ctx, "%d: 3", gproc.Pid())
} else {
m := gproc.NewManager()
p := m.NewProcess(os.Args[0], os.Args, os.Environ())
p.Start(ctx)
p.Wait()
g.Log().Printf(ctx, "%d: child died", gproc.Pid())
}
}

After execution, the terminal prints the following result:

2018-05-18 14:35:41.360 28285: Hi, I am child, waiting 3 seconds to die
2018-05-18 14:35:42.361 28285: 1
2018-05-18 14:35:43.361 28285: 2
2018-05-18 14:35:44.361 28285: 3
2018-05-18 14:35:44.362 28278: child died

Multi-process Management​

In addition to creating subprocesses and managing them, gproc can also manage other processes not created by itself. gproc can manage multiple processes simultaneously. Here we demonstrate the management function with a single process as an example.

  1. We use the gedit software (a commonly used text editor on Linux) to open a file at random. In the process, we see that the process ID of this gedit is 28536.
    $ ps aux | grep gedit
john 28536 3.6 0.6 946208 56412 ? Sl 14:39 0:00 gedit /home/john/Documents/text
  1. Our program is as follows:
package main

import (
"fmt"

"github.com/gogf/gf/v2/os/gproc"
)

func main() {
pid := 28536
m := gproc.NewManager()
m.AddProcess(pid)
m.KillAll()
m.WaitAll()
fmt.Printf("%d was killed\n", pid)
}

After execution, gedit is closed, and the terminal output is:

28536 was killed