exec.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // exec.go
  2. package main
  3. import (
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. )
  8. func main() {
  9. // 1) os.StartProcess //
  10. /*********************/
  11. /* Linux: */
  12. env := os.Environ()
  13. procAttr := &os.ProcAttr{
  14. Env: env,
  15. Files: []*os.File{
  16. os.Stdin,
  17. os.Stdout,
  18. os.Stderr,
  19. },
  20. }
  21. // 1st example: list files
  22. pid, err := os.StartProcess("/bin/ls", []string{"ls", "-l"}, procAttr)
  23. if err != nil {
  24. fmt.Printf("Error %v starting process!", err) //
  25. os.Exit(1)
  26. }
  27. fmt.Printf("The process id is %v", pid)
  28. // 2nd example: show all processes
  29. pid, err = os.StartProcess("/bin/ps", []string{"-e", "-opid,ppid,comm"}, procAttr)
  30. if err != nil {
  31. fmt.Printf("Error %v starting process!", err) //
  32. os.Exit(1)
  33. }
  34. fmt.Printf("The process id is %v", pid)
  35. /* Output 1st:
  36. The process id is &{2054 0}total 2056
  37. -rwxr-xr-x 1 ivo ivo 1157555 2011-07-04 16:48 Mieken_exec
  38. -rw-r--r-- 1 ivo ivo 2124 2011-07-04 16:48 Mieken_exec.go
  39. -rw-r--r-- 1 ivo ivo 18528 2011-07-04 16:48 Mieken_exec_go_.6
  40. -rwxr-xr-x 1 ivo ivo 913920 2011-06-03 16:13 panic.exe
  41. -rw-r--r-- 1 ivo ivo 180 2011-04-11 20:39 panic.go
  42. */
  43. // 2) exec.Run //
  44. /***************/
  45. // Linux: OK, but not for ls ?
  46. // cmd := exec.Command("ls", "-l") // no error, but doesn't show anything ?
  47. // cmd := exec.Command("ls") // no error, but doesn't show anything ?
  48. cmd := exec.Command("gedit") // this opens a gedit-window
  49. err = cmd.Run()
  50. if err != nil {
  51. fmt.Printf("Error %v executing command!", err)
  52. os.Exit(1)
  53. }
  54. fmt.Printf("The command is %v", cmd)
  55. // The command is &{/bin/ls [ls -l] [] <nil> <nil> <nil> 0xf840000210 <nil> true [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [] [] 0xf8400128c0}
  56. }
  57. // in Windows: uitvoering: Error fork/exec /bin/ls: The system cannot find the path specified. starting process!