Execute Shell Commands

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/os/gctx"
  5. "github.com/gogf/gf/v2/os/gproc"
  6. )
  7. func main() {
  8. r, err := gproc.ShellExec(gctx.New(), `sleep 3; echo "hello gf!";`)
  9. fmt.Println("result:", r)
  10. fmt.Println(err)
  11. }

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

  1. result: hello gf!
  2. <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.

  1. package main
  2. import (
  3. "os"
  4. "time"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gctx"
  7. "github.com/gogf/gf/v2/os/gproc"
  8. )
  9. func main() {
  10. var ctx = gctx.New()
  11. if gproc.IsChild() {
  12. g.Log().Printf(ctx, "%d: Hi, I am child, waiting 3 seconds to die", gproc.Pid())
  13. time.Sleep(time.Second)
  14. g.Log().Printf(ctx, "%d: 1", gproc.Pid())
  15. time.Sleep(time.Second)
  16. g.Log().Printf(ctx, "%d: 2", gproc.Pid())
  17. time.Sleep(time.Second)
  18. g.Log().Printf(ctx, "%d: 3", gproc.Pid())
  19. } else {
  20. m := gproc.NewManager()
  21. p := m.NewProcess(os.Args[0], os.Args, os.Environ())
  22. p.Start(ctx)
  23. p.Wait()
  24. g.Log().Printf(ctx, "%d: child died", gproc.Pid())
  25. }
  26. }

After execution, the terminal prints the following result:

  1. 2018-05-18 14:35:41.360 28285: Hi, I am child, waiting 3 seconds to die
  2. 2018-05-18 14:35:42.361 28285: 1
  3. 2018-05-18 14:35:43.361 28285: 2
  4. 2018-05-18 14:35:44.361 28285: 3
  5. 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.
  1. $ ps aux | grep gedit
  2. john 28536 3.6 0.6 946208 56412 ? Sl 14:39 0:00 gedit /home/john/Documents/text
  1. Our program is as follows:
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/os/gproc"
  5. )
  6. func main() {
  7. pid := 28536
  8. m := gproc.NewManager()
  9. m.AddProcess(pid)
  10. m.KillAll()
  11. m.WaitAll()
  12. fmt.Printf("%d was killed\n", pid)
  13. }

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

  1. 28536 was killed