Golang Linux Shell編程(一)
阿新 • • 發佈:2018-02-13
name 等待 inux 執行 shell. 標準輸出 包裝 pos github
1.調用系統命令
exec包執行外部命令,它將os.StartProcess進行包裝使得它更容易映射到stdin和stdout,並且利用pipe連接i/o
func Command(name string, arg ...string) *Cmd {}
調用系統命令:
package main
import (
"os/exec"
"log"
"fmt"
)
func main() {
cmd := exec.Command("ls","-l")
out,err := cmd.CombinedOutput()//標準輸出 標準錯誤 組合
//out, err := cmd.Output()
//Output()和CombinedOutput()不能夠同時使用,
// 因為command的標準輸出只能有一個,同時使用的話便會定義了兩個,便會報錯
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
}
2.交互式調用系統命令
package main
import (
"os/exec"
"bufio"
"fmt"
"log"
"time"
)
func main() {
cmd := exec.Command("ls","-l")
out,_ :=cmd.StdoutPipe() //StdoutPipe返回一個連接到command標準輸出的管道pipe
if err := cmd.Start();err != nil {
log.Fatal("start error:%v",err)
}
f := bufio.NewReader(out)
for {
line,err := f.ReadString(‘\n‘)
if err != nil {
break
}
fmt.Print(line)
}
time.Sleep(time.Hour)
//cmd.Wait()
//Wait等待command退出,他必須和Start一起使用,
//如果命令能夠順利執行完並順利退出則返回nil,否則的話便會返回error,其中Wait會是放掉所有與cmd命令相關的資源
}
不加wait()會產生僵屍進程,3466 defunct 僵屍進程,wait收屍
go build cmd.go
./cmd
[root@greg02 ]#ps -ef |grep cmd2
root 3466 2539 0 20:37 pts/0 00:00:00 ./cmd2
[root@greg02 ]#ps -ef |grep ls
root 683 1 0 18:43 ? 00:00:21 /usr/bin/vmtoolsd
root 3470 3466 0 20:37 pts/0 00:00:00 [ls] <defunct>
3.自制bash
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
)
func main() {
host, _ := os.Hostname()
prompt := fmt.Sprintf("[ningxin@%s]$ ", host)
r := bufio.NewScanner(os.Stdin)
//r := bufio.NewReader(os.Stdin)
for {
fmt.Print(prompt)
if !r.Scan() {
break
}
line := r.Text()
// line, _ := r.ReadString(‘\n‘)
// line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
args := strings.Fields(line)
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
fmt.Println(err)
}
}
}
4.管道pipe
package main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
)
func main() {
line := "ls | grep f"
cmds := strings.Split(line, "|")
s1 := strings.Fields(cmds[0])
s2 := strings.Fields(cmds[1])
fmt.Println(s1)
fmt.Println(s2)
r, w := io.Pipe()
cmd1 := exec.Command(s1[0], s1[1:]...)
cmd2 := exec.Command(s2[0], s2[1:]...)
//cmd1 := exec.Command("ls")
//cmd2 := exec.Command("grep","f")
cmd1.Stdin = os.Stdin
cmd1.Stdout = w
cmd2.Stdin = r
cmd2.Stdout = os.Stdout
cmd1.Start()
cmd2.Start()
log.Print("start")
cmd1.Wait()
cmd2.Wait()
}
5.shell.go
https://github.com/ningxin1718/gosubshell
Golang Linux Shell編程(一)