// run runs the command argv, resolving argv[0] if necessary by searching $PATH. // It provides input on standard input to the command. func run(argv []string, input []byte) (out string, err os.Error) { if len(argv) < 1 { err = os.EINVAL goto Error } prog, ok := lookPathCache[argv[0]] if !ok { prog, err = exec.LookPath(argv[0]) if err != nil { goto Error } lookPathCache[argv[0]] = prog } // fmt.Fprintf(os.Stderr, "%v\n", argv); var cmd *exec.Cmd if len(input) == 0 { cmd, err = exec.Run(prog, argv, os.Environ(), "", exec.DevNull, exec.Pipe, exec.MergeWithStdout) if err != nil { goto Error } } else { cmd, err = exec.Run(prog, argv, os.Environ(), "", exec.Pipe, exec.Pipe, exec.MergeWithStdout) if err != nil { goto Error } go func() { cmd.Stdin.Write(input) cmd.Stdin.Close() }() } defer cmd.Close() var buf bytes.Buffer _, err = io.Copy(&buf, cmd.Stdout) out = buf.String() if err != nil { cmd.Wait(0) goto Error } w, err := cmd.Wait(0) if err != nil { goto Error } if !w.Exited() || w.ExitStatus() != 0 { err = w goto Error } return Error: err = &runError{copy(argv), err} return }
func main() { ts, e := os.Open("tests", os.O_RDONLY, 0) error.FailOn(e) error.FailOn(os.RemoveAll("tests/tmp")) ds, e := ts.Readdir(-1) error.FailOn(e) // Set up an environment with an appropriate path wd, e := os.Getwd() error.FailOn(e) os.Setenv("PATH", path.Join(wd, "bin")+":"+os.Getenv("PATH")) for _, d := range ds { if d.IsRegular() && (d.Permission()&1) == 1 && endsWith(d.Name, ".sh") { basename := d.Name[0 : len(d.Name)-3] fmt.Printf("Running %s... ", basename) dirname := path.Join("tests/tmp", basename) error.FailOn(os.MkdirAll(dirname, 0777)) pid, e := exec.Run(path.Join(wd, "tests", d.Name), []string{}, os.Environ(), dirname, exec.DevNull, exec.Pipe, exec.MergeWithStdout) error.FailOn(e) o, e := ioutil.ReadAll(pid.Stdout) error.FailOn(e) ret, e := pid.Wait(0) error.FailOn(e) if ret.ExitStatus() != 0 { error.Print("FAILED!\n", string(o)) error.Print("Test '", basename, "' failed!") exit.Exit(1) } fmt.Println("passed.") } } }
func runShellCommand(argv []string) map[string]string { result := map[string]string{ "out": "", "err": ""} app := argv[0] home := fmt.Sprintf("HOME=%v", os.Getenv("HOME")) path := fmt.Sprintf("PATH=%v", os.Getenv("PATH")) env := []string{home, path} cmd, err := exec.Run(app, argv, env, "", exec.DevNull, exec.Pipe, exec.Pipe) if err != nil { fmt.Fprintln(os.Stderr, err.String()) result["err"] = err.String() return result } var b1 bytes.Buffer io.Copy(&b1, cmd.Stdout) fmt.Println(b1.String()) result["out"] = b1.String() var b2 bytes.Buffer io.Copy(&b2, cmd.Stderr) fmt.Println(b2.String()) result["err"] = b2.String() cmd.Close() return result }
func justrun(cmd string, args ...string) os.Error { abscmd, err := exec.LookPath(cmd) if err != nil { return os.NewError("Couldn't find " + cmd + ": " + err.String()) } cmdargs := make([]string, len(args)+1) cmdargs[0] = cmd for i, a := range args { cmdargs[i+1] = a } pid, err := exec.Run(abscmd, cmdargs, nil, "", exec.PassThrough, exec.PassThrough, exec.PassThrough) if err != nil { return err } wmsg, err := pid.Wait(0) if err != nil { return err } if wmsg.ExitStatus() != 0 { return os.NewError(cmd + " exited with status " + fmt.Sprint(wmsg.ExitStatus())) } return nil }
func (p *ProcessStarter) Stop(com *Command, reply *string) os.Error { fmt.Printf("try stopping process\n") data, ok := processMap[com.name] if !ok { fmt.Printf("server unknown:%s", com.name) } else { if data.cmd != nil && data.cmd.Pid > 0 { fmt.Printf("kill pid server %d:", data.cmd.Pid) var pid string = fmt.Sprintf("%d", data.cmd.Pid) println(pid) args := []string{com.command, "--stop", pid} env := []string{"DYLD_LIBRARY_PATH=/Users/jholscher/Documents/bripper/install/lib/"} _, err := exec.Run(com.command, args, env, com.dir, exec.DevNull, exec.Pipe, exec.PassThrough) if err != nil { fmt.Println("error stop process") } else { //fmt.Println("process stopped") } // syscall.Kill(data.cmd.Pid, 15) } else { fmt.Printf("failed to stop the process, because one of the following data is nil or lower 0 [%s,%d]", data.cmd, data.cmd.Pid) } } return nil }
func mustRunDoozer(listen, web, attach string) *exec.Cmd { exe, err := exec.LookPath("doozerd") if err != nil { panic(err) } args := []string{ "doozerd", "-l=127.0.0.1:" + listen, "-w=127.0.0.1:" + web, } if attach != "" { args = append(args, "-a", "127.0.0.1:"+attach) } cmd, err := exec.Run( exe, args, nil, ".", exec.PassThrough, exec.PassThrough, exec.PassThrough, ) if err != nil { panic(err) } return cmd }
func ExecRead(cmd string, args ...string) (out []byte, err os.Error) { abscmd, err := exec.LookPath(cmd) if err != nil { return out, os.NewError("Couldn't find " + cmd + ": " + err.String()) } cmdargs := make([]string, len(args)+1) cmdargs[0] = cmd for i, a := range args { cmdargs[i+1] = a } printexec(cmd, args) pid, err := exec.Run(abscmd, cmdargs, nil, "", exec.PassThrough, exec.Pipe, exec.PassThrough) if err != nil { return } out, err = ioutil.ReadAll(pid.Stdout) if err != nil { return } ws, err := pid.Wait(0) // could have been os.WRUSAGE if err != nil { return } if ws.ExitStatus() != 0 { err = os.NewError(cmd + " exited with status " + strconv.Itoa(ws.ExitStatus())) } return out, nil }
func main() { flag.Parse() cwd, _ := os.Getwd() binary, _ := exec.LookPath(flag.Args()[0]) for { cmd, _ := exec.Run(binary, flag.Args(), nil, cwd, exec.PassThrough, exec.PassThrough, exec.PassThrough) pid := cmd.Process.Pid extras := make(ABC, 0) if *httpTimeoutUrl != "" { extras = append(extras, setupHttpTimeoutCheck(pid)) } if *httpStatusUrl != "" { extras = append(extras, setupHttpStatusCheck(pid)) } if *maxMemory > 0 { extras = append(extras, setupMaxMemoryCheck(pid)) } cmd.Wait(os.WSTOPPED) println("Process died, restarting.") extras.closeAll() } }
func diff(b1, b2 []byte) (data []byte, err os.Error) { f1, err := ioutil.TempFile("", "gofix") if err != nil { return nil, err } defer os.Remove(f1.Name()) defer f1.Close() f2, err := ioutil.TempFile("", "gofix") if err != nil { return nil, err } defer os.Remove(f2.Name()) defer f2.Close() f1.Write(b1) f2.Write(b2) diffcmd, err := exec.LookPath("diff") if err != nil { return nil, err } c, err := exec.Run(diffcmd, []string{"diff", f1.Name(), f2.Name()}, nil, "", exec.DevNull, exec.Pipe, exec.MergeWithStdout) if err != nil { return nil, err } defer c.Close() return ioutil.ReadAll(c.Stdout) }
// Build runs makepkg on the specified srcdir. A slice of package paths are // returned. These are the paths to the binary packages that are built. Packages // with multiple pkgnames build multiple packages, hence the use of a slice. // If an error occurs, returns nil and the error. // // Notice that we do not actually set PKGDEST ourselves, this should be done // before calling this function. Otherwise the built package will just end up // in the package source directory. Maybe. func (builder *PackageBuilder) Build(srcdir string) ([]string, os.Error) { // Create a tempfile and hook it into our bash tomfoolery. pathfile, err := NewPkgPathFile() if err != nil { return nil, err } defer pathfile.Cleanup() // Call our included utility, mawmakepkg which wraps makepkg to drop priveledges // and print the paths of built packages to our tempfile. args := []string{MawMakepkgPath, pathfile.Name(), "-s", "-m", "-f"} cmd, err := exec.Run(MawMakepkgPath, args, nil, srcdir, exec.PassThrough, exec.PassThrough, exec.PassThrough) if err != nil { return nil, err } defer cmd.Process.Release() waitmsg, err := cmd.Wait(0) if code := waitmsg.ExitStatus(); code != 0 { return nil, os.NewError("makepkg failed") } return pathfile.ReadLines() }
// genRun implements run and tryRun. func genRun(dir string, stdin []byte, cmd []string, quiet bool) os.Error { bin, err := exec.LookPath(cmd[0]) if err != nil { return err } p, err := exec.Run(bin, cmd, os.Environ(), dir, exec.Pipe, exec.Pipe, exec.MergeWithStdout) if *verbose { fmt.Fprintf(os.Stderr, "%s: %s; %s %s\n", argv0, dir, bin, strings.Join(cmd[1:], " ")) } if err != nil { return err } go func() { p.Stdin.Write(stdin) p.Stdin.Close() }() var buf bytes.Buffer io.Copy(&buf, p.Stdout) io.Copy(&buf, p.Stdout) w, err := p.Wait(0) p.Close() if !w.Exited() || w.ExitStatus() != 0 { if !quiet || *verbose { if dir != "" { dir = "cd " + dir + "; " } fmt.Fprintf(os.Stderr, "%s: === %s%s\n", argv0, dir, strings.Join(cmd, " ")) os.Stderr.Write(buf.Bytes()) fmt.Fprintf(os.Stderr, "--- %s\n", w) } return os.ErrorString("running " + cmd[0] + ": " + w.String()) } return nil }
func build(gcfile string, opts []string, proFileName string, files []string, envv []string, dir string) (status syscall.WaitStatus, err os.Error) { arg := []string{gcfile, "-o", proFileName} for _, v := range opts { arg = append(arg, v) } for _, v := range files { arg = append(arg, string(v)) } fmt.Println("\t", arg) var cmd *exec.Cmd cmd, err = exec.Run(gcfile, arg[:], envv[:], dir, 0, 1, 2) if err != nil { fmt.Printf("Error, %s", err) return } defer cmd.Close() var wait *os.Waitmsg wait, err = cmd.Wait(0) if err != nil { fmt.Printf("Error, %s", err) return } status = wait.WaitStatus return }
// run executes the specified command and returns its output and an error. func run(cmd ...string) ([]byte, os.Error) { // find the specified binary bin, err := exec.LookPath(cmd[0]) if err != nil { // report binary as well as the error return nil, os.NewError(cmd[0] + ": " + err.String()) } // run the binary and read its combined stdout and stderr into a buffer p, err := exec.Run(bin, cmd, os.Environ(), "", exec.DevNull, exec.Pipe, exec.MergeWithStdout) if err != nil { return nil, err } var buf bytes.Buffer io.Copy(&buf, p.Stdout) w, err := p.Wait(0) p.Close() if err != nil { return nil, err } // set the error return value if the program had a non-zero exit status if !w.Exited() || w.ExitStatus() != 0 { err = os.ErrorString("running " + cmd[0] + ": " + w.String()) } return buf.Bytes(), err }
func Run(prog, dir string, argv []string) ([]string, os.Error) { cmd, err := exec.Run(prog, argv, nil, dir, exec.Pipe, exec.Pipe, exec.Pipe) if err != nil { if cmd != nil { cmd.Close() } return []string{""}, err } liner, err := bufio.NewReaderSize(cmd.Stdout, 2000) if err != nil { cmd.Close() return nil, err } r := []string{} var l []byte for { l, _, err = liner.ReadLine() if err != nil { break } r = append(r, string(l)) } if err != nil && err != os.EOF { cmd.Close() return nil, err } err = cmd.Close() return r, err }
func RunExternalDump(cmd, wd string, argv []string, dump io.Writer) (err os.Error) { var p *exec.Cmd p, err = exec.Run(cmd, argv, nil, wd, exec.PassThrough, exec.Pipe, exec.PassThrough) if err != nil { return } if p != nil { src := p.Stdout buffer := make([]byte, 1024) for { n, cpErr := src.Read(buffer) if cpErr != nil { break } _, cpErr = dump.Write(buffer[0:n]) if cpErr != nil { break } } var wmsg *os.Waitmsg wmsg, err = p.Wait(0) if wmsg.ExitStatus() != 0 { err = os.NewError(fmt.Sprintf("%v: %s\n", argv, wmsg.String())) return } if err != nil { return } } return }
// Format takes a markdown-formatted string and returns an equivalent // HTML-formatted string. // // TODO write built-in markdown implementation, to avoid forking for every // post func Format(md string) (html string, err os.Error) { cmdName, err := exec.LookPath("markdown") if err != nil { return } cmd, err := exec.Run( cmdName, []string{}, os.Environ(), ".", exec.Pipe, exec.Pipe, exec.PassThrough, ) if err != nil { return } cmd.Stdin.WriteString(md) cmd.Stdin.Close() b, err := ioutil.ReadAll(cmd.Stdout) if err != nil { return } html = string(b) err = cmd.Close() return }
func WriteReadS(arg1 string, inp string, args []string) (output string, e os.Error) { debug.Println("calling git",arg1,args) args = stringslice.Cat([]string{"git", arg1}, args) output = "" // empty output if we have an error... git, e := exec.LookPath("git") if e != nil { e = explain("exec.LookPath",e); return } pid,e := exec.Run(git, args, os.Environ(), ".", exec.Pipe, exec.Pipe, exec.PassThrough) if e != nil { announce(e); return } _,e = fmt.Fprint(pid.Stdin, inp) if e != nil { announce(e); return } e = pid.Stdin.Close() if e != nil { announce(e); return } o,e := ioutil.ReadAll(pid.Stdout) output = string(o) if e != nil { announce(e); return } ws,e := pid.Wait(0) // could have been os.WRUSAGE if e != nil { announce(e); return } if ws.ExitStatus() != 0 { e = os.NewError(fmt.Sprintf("git exited with '%v'",ws.ExitStatus())) announce(e) return } return }
/* This function does exactly the same as "make clean". */ func clean() { bashBin, err := exec.LookPath("bash") if err != nil { logger.Error("Need bash to clean.\n") os.Exit(127) } argv := []string{bashBin, "-c", "commandhere"} if *flagVerboseMode { argv[2] = "rm -rfv *.[568]" } else { argv[2] = "rm -rf *.[568]" } logger.Info("Running: %v\n", argv[2:]) cmd, err := exec.Run(bashBin, argv, os.Environ(), rootPath, exec.DevNull, exec.PassThrough, exec.PassThrough) if err != nil { logger.Error("%s\n", err) os.Exit(1) } waitmsg, err := cmd.Wait(0) if err != nil { logger.Error("Couldn't delete files: %s\n", err) os.Exit(1) } if waitmsg.ExitStatus() != 0 { logger.Error("rm returned with errors.\n") os.Exit(waitmsg.ExitStatus()) } }
func run(name string, args ...string) string { path, err := exec.LookPath(name) if err != nil { panic(err) } cwd, err := os.Getwd() if err != nil { panic(err) } p, err := exec.Run(path, append([]string{name}, args...), os.Environ(), cwd, exec.Pipe, exec.Pipe, exec.Pipe) if err != nil { panic(err) } defer p.Close() data, err := ioutil.ReadAll(p.Stdout) if err != nil { panic(err) } return strings.TrimSpace(string(data)) }
func runWithOutput(binary string, args []string) string { cwd, _ := os.Getwd() cmd, _ := exec.Run(binary, args, nil, cwd, exec.PassThrough, exec.Pipe, exec.PassThrough) cmd.Wait(os.WSTOPPED) stdout, _ := ioutil.ReadAll(cmd.Stdout) return strings.Trim(string(stdout), " \n") }
// runLog runs a process and returns the combined stdout/stderr, // as well as writing it to logfile (if specified). func runLog(envv []string, logfile, dir string, argv ...string) (output string, exitStatus int, err os.Error) { if *verbose { log.Println("runLog", argv) } bin, err := lookPath(argv[0]) if err != nil { return } p, err := exec.Run(bin, argv, envv, dir, exec.DevNull, exec.Pipe, exec.MergeWithStdout) if err != nil { return } defer p.Close() b := new(bytes.Buffer) var w io.Writer = b if logfile != "" { f, err := os.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { return } defer f.Close() w = io.MultiWriter(f, b) } _, err = io.Copy(w, p.Stdout) if err != nil { return } wait, err := p.Wait(0) if err != nil { return } return b.String(), wait.WaitStatus.ExitStatus(), nil }
func (pf *PacmanFetcher) findPackageUrl(pkgname string) (string, FetchError) { args := []string{"pacman", "-S", "--print", pkgname} cmd, err := exec.Run("/usr/bin/pacman", args, nil, "", exec.DevNull, exec.Pipe, exec.Pipe) if err != nil { return "", FetchErrorWrap(pkgname, err) } defer cmd.Close() waitmsg, err := cmd.Wait(0) if err != nil { return "", FetchErrorWrap(pkgname, err) } if code := waitmsg.ExitStatus(); code != 0 { errline := pf.readLine(cmd.Stderr) if errline == "error: target not found: "+pkgname { return "", NotFoundError(pkgname) } return "", NewFetchError(pkgname, "pacman "+errline) } url := pf.readLine(cmd.Stdout) return url, nil }
func init() { cache := make(map[string]string) translations := make(map[string]string) for i := '1'; i < '7'; i++ { for sv := 0; sv <= bridge.NoTrump; sv++ { stringi := string([]byte{byte(i)}) spoken := stringi + " " + bridge.SuitName[sv] + "." translations[stringi+bridge.SuitHTML[sv]] = spoken translations[stringi+bridge.SuitLetter[sv]] = spoken translations[stringi+bridge.SuitColorHTML[sv]] = spoken } } translations[" P"] = "Pass." translations["P"] = "Pass." translations[" X"] = "Double!" translations["X"] = "Double!" translations["XX"] = "Redouble!" espeak, err := exec.LookPath("espeak") if err == nil { go func() { for { req := <-seek_speech bid := req.bid if sp, ok := translations[bid]; ok { bid = sp } fmt.Println("I am speaking:", bid) if s, ok := cache[req.bid]; ok { req.answer <- answertype{s, nil} } else { c, err := exec.Run(espeak, []string{"espeak", "--stdout"}, nil, "", exec.Pipe, exec.Pipe, exec.PassThrough) if err != nil { req.answer <- answertype{"", err} continue } defer c.Close() fmt.Fprintln(c.Stdin, bid) c.Stdin.Close() o, err := ioutil.ReadAll(c.Stdout) if err != nil { req.answer <- answertype{"", err} continue } out := string(o) cache[req.bid] = out req.answer <- answertype{out, nil} } } }() } else { go func() { fmt.Println("We won't be able to speak, since I can't find espeak!", err) for { req := <-seek_speech req.answer <- answertype{"", os.NewError("Cannot find espeak in path.")} } }() } }
func main() { commands := []string{ `ls /home`, `ls '/home'`, `ls -l /home`, `echo 'Hello, one and all!'`, `which python`, // Outputs "hello, world\n" instead of "\n" `python -c print 'hello, world'`, // Outputs "\n" instead of "hello, world\n" `python -c "print 'hello, world'"`, } for ndx, c := range commands { fmt.Printf("Command %d of %d: %s\n", ndx+1, len(commands), c) // When I replace 3 with -1, the last 2 commands produce a Python error argv := strings.Split(c, " ", 3) bin, err := exec.LookPath(argv[0]) if cmd, e := exec.Run(bin, argv, nil, "", exec.DevNull, exec.Pipe, exec.MergeWithStdout); e == nil && err == nil { body, _ := ioutil.ReadAll(cmd.Stdout) fmt.Printf("%s\n", string(body)) } else { fmt.Printf("e: %v", e) fmt.Printf("err: %v", err) } } }
/* Creates a .a file for a single GoPackage */ func packLib(pack *godata.GoPackage) { var objDir string = "" //outputDirPrefix + getObjDir(); logger.Info("Creating %s.a...\n", pack.Name) argv := []string{ gopackBin, "crg", // create new go archive outputDirPrefix + pack.Name + ".a", objDir + pack.Name + objExt, } logger.Debug("%s\n", getCommandline(argv)) cmd, err := exec.Run(gopackBin, argv, os.Environ(), rootPath, exec.DevNull, exec.PassThrough, exec.PassThrough) if err != nil { logger.Error("%s\n", err) os.Exit(1) } waitmsg, err := cmd.Wait(0) if err != nil { logger.Error("gopack execution error (%s), aborting.\n", err) os.Exit(1) } if waitmsg.ExitStatus() != 0 { logger.Error("gopack returned with errors, aborting.\n") os.Exit(waitmsg.ExitStatus()) } os.Remove(objDir + pack.Name + objExt) }
func modifyDaemon(argv []string) (int, os.Error) { daemon := fmt.Sprintf("%s%s", etcrcd, argv[0]) p, err := exec.Run(daemon, argv, os.Environ(), etcrcd, 0, 1, 2) w, err := p.Wait(0) return w.ExitStatus(), err }
/* Run stty with the given argument string */ func stty(mode string) { cmd, err := exec.Run("/bin/stty", []string{"stty", mode}, os.Environ(), "", exec.PassThrough, exec.PassThrough, exec.PassThrough) if err != nil { fmt.Print(err) os.Exit(-1) } cmd.Close() }
func main() { if cmd, e := exec.Run("/bin/ls", nil, nil, "", exec.Pipe, exec.MergeWithStdout, 1); e == nil { b, _ := ioutil.ReadAll(cmd.Stdout) println("output: " + string(b)) } else { fmt.Printf("Error: %v\n", e) } }
func callWOL(argc int, argv []string) (result []string) { rechnerInfo := getInfoByRechnername(argv[1]) p, e := exec.Run(ETHERWAKE, []string{ETHERWAKE, rechnerInfo[6]}, nil, "/", exec.DevNull, exec.DevNull, exec.DevNull) if e != nil { return []string{"#Error calling etherwake"} } p.Wait(0) return []string{"OK"} }
func main() { bin, err := exec.LookPath("python") if cmd, e := exec.Run(bin, []string{"", "-c", `print 'hello world'`}, nil, "", exec.DevNull, exec.Pipe, exec.MergeWithStdout); e == nil && err == nil { b, _ := ioutil.ReadAll(cmd.Stdout) fmt.Printf("output: %s\n", string(b)) } else { fmt.Printf("e: %v\n", e) fmt.Printf("err: %v\n", err) } }