func TestSysCall(t *testing.T) {
binary,err :=exec.LookPath("ping")
if err != nil {
fmt.Println(err)
}
args := []string{"ping","pue7ms.dnslog.cn"}
// Environ 返回代表环境的字符串副本,格式为“key=value”。
env :=os.Environ()
if err:=syscall.Exec(binary,args,env);err!=nil{
fmt.Println(err)
}
}
func TestSysCallExecFork(t *testing.T) {
binary,err :=exec.LookPath("ping")
if err != nil {
fmt.Println(err)
}
sttyArgs := syscall.ProcAttr{
Env: []string{},
Files: []uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd()},
}
args := []string{"ping","452gyr.dnslog.cn"}
syscall.ForkExec(binary,args,&sttyArgs)
}
func TestName(t *testing.T) {
name := "ls"
args := []string{"/"}
attr := &os.ProcAttr{}
proc, err := os.StartProcess(name, args, attr)
if err != nil {
fmt.Println(err)
}
_, err = proc.Wait()
if err != nil {
fmt.Println(err)
}
}
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error)
StartProcess 使用由 name ,argv 和 attr 指定的程序,参数和属性启动一个新进程。StartProcess 是一个低级别的界面。os/exec 软件包提供更高级的接口。
func main() {
cmd := exec.Command("ls", "-l", "/var/log/")
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Printf("combined out:\n%s\n", string(out))
log.Fatalf("cmd.Run() failed with %s\n", err)
}
fmt.Printf("combined out:\n%s\n", string(out))
}
CommandContext类似于Command,但包含上下文。
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
// This will fail after 100 milliseconds. The 5 second sleep
// will be interrupted.
}
}