Calling Command-Line Programs in Go

2021年10月5日 3047点热度 2人点赞 0条评论
内容目录

In the context of Linux, here's how to invoke a command-line program in Go, with the example code as follows:

package main

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

func main() {
	cmd := exec.Command("top")

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}
}

First, use cmd := exec.Command("top") to specify the command-line program you want to use.

You can also set its parameters:

	cmd := exec.Command("top", "-n", "1")

To "proxy" the command-line program within the GO program—allowing users to execute commands or interact in the program's console as if they were executing commands directly—you need to set the command-line console IO to the current Go program's console IO.

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

Additionally, when making system calls, you can set certain parameters. For example, on Linux, supporting namespaces, you can achieve process isolation similar to Docker:

	cmd.SysProcAttr = &syscall.SysProcAttr{
		Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWIPC,
	}

The complete code is as follows:

package main

import (
	"log"
	"os"
	"os/exec"
	"syscall"
)

func main() {
	cmd := exec.Command("sh")
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWIPC,
	}

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}
}

痴者工良

高级程序员劝退师

文章评论