func git_from_net(url string) string { var args [3]string args[0] = "git" args[1] = "clone" args[2] = url var fds []*os.File = new([3]*os.File) fds[0] = os.Stdin fds[1] = os.Stdout fds[2] = os.Stderr _, str := path.Split(url) name := strings.Split(str, ".", -1)[0] var git_path string switch os.Getenv("GOOS") { case "darwin": git_path = "/usr/local/git/bin/git" break case "linux": git_path = "/opt/local/bin/git" break } /* Replace this with git's full path, or use a shell, and then call git in the args */ pid, err := os.ForkExec(git_path, &args, os.Envs, os.Getenv("GOROOT")+"/src/pkg/", fds) if err != nil { log.Exit(err) } os.Wait(pid, 0) return string(os.Getenv("GOROOT") + "/src/pkg/" + name) }
// Return the output from running the given command func GetOutput(args []string) (output string, error os.Error) { read_pipe, write_pipe, err := os.Pipe() if err != nil { goto Error } defer read_pipe.Close() pid, err := os.ForkExec(args[0], args, os.Environ(), ".", []*os.File{nil, write_pipe, nil}) if err != nil { write_pipe.Close() goto Error } _, err = os.Wait(pid, 0) write_pipe.Close() if err != nil { goto Error } buffer := &bytes.Buffer{} _, err = io.Copy(buffer, read_pipe) if err != nil { goto Error } output = buffer.String() return output, nil Error: return "", &CommandError{args[0], args} }
// exec a program, redirecting output func DateServer(c *http.Conn, req *http.Request) { c.SetHeader("content-type", "text/plain; charset=utf-8") r, w, err := os.Pipe() if err != nil { fmt.Fprintf(c, "pipe: %s\n", err) return } pid, err := os.ForkExec("/bin/date", []string{"date"}, os.Environ(), "", []*os.File{nil, w, w}) defer r.Close() w.Close() if err != nil { fmt.Fprintf(c, "fork/exec: %s\n", err) return } io.Copy(c, r) wait, err := os.Wait(pid, 0) if err != nil { fmt.Fprintf(c, "wait: %s\n", err) return } if !wait.Exited() || wait.ExitStatus() != 0 { fmt.Fprintf(c, "date: %v\n", wait) return } }
// wait waits for a wait event from this thread and sends it on the // debug events channel for this thread's process. This should be // started in its own goroutine when the attached thread enters a // running state. The goroutine will exit as soon as it sends a debug // event. func (t *thread) wait() { for { var ev debugEvent ev.t = t t.logTrace("beginning wait") ev.Waitmsg, ev.err = os.Wait(t.tid, syscall.WALL) if ev.err == nil && ev.Pid != t.tid { panic(fmt.Sprint("Wait returned pid ", ev.Pid, " wanted ", t.tid)) } if ev.StopSignal() == syscall.SIGSTOP && t.ignoreNextSigstop { // Spurious SIGSTOP. See Thread.Stop(). t.ignoreNextSigstop = false err := t.ptraceCont() if err == nil { continue } // If we failed to continue, just let // the stop go through so we can // update the thread's state. } if !<-t.proc.ready { // The monitor exited break } t.proc.debugEvents <- &ev break } }
func Serve(conn net.Conn) { defer conn.Close() tty, pid, err := term.ForkPty( "/bin/login", []string{"/bin/login"}, term.DefaultAttributes(), term.NewWindowSize(80, 25)) if err != nil { fmt.Fprintf(os.Stderr, "ForkExecPty failed: %v\n", err) return } defer os.Wait(pid, 0) defer syscall.Kill(pid, 9) running := true go func() { buffer := make([]byte, 64) for n, e := conn.Read(buffer); e == nil && running; n, e = conn.Read(buffer) { tty.Write(buffer[:n]) } running = false }() go func() { buffer := make([]byte, 64) var n int var e os.Error for n, e = tty.Read(buffer); e == nil && running; n, e = tty.Read(buffer) { conn.Write(buffer[:n]) } running = false }() tick := time.NewTicker(1e9) for running { select { case <-tick.C: msg, err := os.Wait(pid, os.WNOHANG) if err == nil && msg.Pid == pid { running = false } } } }
func (mon *monitor) wait(pid int, e exiteder) { w, err := os.Wait(pid, 0) if err != nil { mon.logger.Println(err) return } mon.exitCh <- exit{e, w} }
func runSystemCommand(argv []string, dir string) string { lookedPath, _ := exec.LookPath(argv[0]) r, w, _ := os.Pipe() pid, _ := os.ForkExec(lookedPath, argv, nil, dir, []*os.File{nil, w, w}) w.Close() os.Wait(pid, 0) var b bytes.Buffer io.Copy(&b, r) return b.String() }
// Wait waits for the running command p, // returning the Waitmsg returned by os.Wait and an error. // The options are passed through to os.Wait. // Setting options to 0 waits for p to exit; // other options cause Wait to return for other // process events; see package os for details. func (p *Cmd) Wait(options int) (*os.Waitmsg, os.Error) { if p.Pid <= 0 { return nil, os.ErrorString("exec: invalid use of Cmd.Wait") } w, err := os.Wait(p.Pid, options) if w != nil && (w.Exited() || w.Signaled()) { p.Pid = -1 } return w, err }
func stage_check(cpid int, err os.Error, stage string) { if err == nil { lolf, _ := os.Wait(cpid, 0) if lolf.ExitStatus() != 0 { fmt.Printf("Failed to %s.\n", stage) os.Exit(lolf.ExitStatus()) } } else { fmt.Println(err) os.Exit(1) } }
func TestTrue(t *testing.T) { if !hasProc() { return } cx := Context{} pid, err := cx.ForkExec("/bin/true", nil) assert.Equal(t, nil, err) assert.T(t, pid > 0) w, err := os.Wait(pid, 0) assert.Equal(t, true, w.Exited()) assert.Equal(t, 0, w.ExitStatus()) }
func UnmountFuse(mountpoint string) (err os.Error) { var pid int fmt.Println("Unmounting", mountpoint, "...") for i := 0; i < len(paths); i++ { var args []string = []string{paths[i], "-u", mountpoint} pid, err = os.ForkExec(paths[i], args, []string{}, "", []*os.File{os.Stdin, os.Stdout, os.Stderr}) if err == nil { os.Wait(pid, 0) return err } } return err }
func privilegedUnmount(mountPoint string) error { dir, _ := filepath.Split(mountPoint) proc, err := os.StartProcess(umountBinary, []string{umountBinary, mountPoint}, &os.ProcAttr{Dir: dir, Files: []*os.File{nil, nil, os.Stderr}}) if err != nil { return err } w, err := os.Wait(proc.Pid, 0) if w.ExitStatus() != 0 { return fmt.Errorf("umount exited with code %d\n", w.ExitStatus()) } return err }
func main() { checkArgs() output, absError := abspath(*outputDir) if absError != nil { showErrorAndQuit(absError.String(), -1) } programPath, programError := getProgramPath() if programError != nil { showErrorAndQuit(programError.String(), -1) } erlPath, pathError := exec.LookPath("erl") if pathError != nil { showErrorAndQuit("Can't find erl program", -1) } head := []string{erlPath, "-run", "efene", "main", *outputType, output} tail := []string{"-run", "init", "stop", "-noshell"} start := len(head) + flag.NArg() args := make([]string, len(head)+len(tail)+flag.NArg()) for i := 0; i < len(head); i++ { args[i] = head[i] } for i := len(head); i < len(head)+flag.NArg(); i++ { args[i], _ = abspath(flag.Arg(i - len(head))) } for i := start; i < start+len(tail); i++ { args[i] = tail[i-start] } if *verbose { fmt.Println("cd " + programPath) fmt.Print(erlPath + " ") printArray(args, true) } pid, error := os.ForkExec(erlPath, args, os.Environ(), programPath, []*os.File{os.Stdin, os.Stdout, os.Stderr}) if error != nil { showErrorAndQuit(error.String(), -1) } os.Wait(pid, 0) }
// run runs the command argv, feeding in stdin on standard input. // It returns the output to standard output and standard error. // ok indicates whether the command exited successfully. func run(stdin []byte, argv []string) (stdout, stderr []byte, ok bool) { cmd, err := exec.LookPath(argv[0]); if err != nil { fatal("exec %s: %s", argv[0], err); } r0, w0, err := os.Pipe(); if err != nil { fatal("%s", err); } r1, w1, err := os.Pipe(); if err != nil { fatal("%s", err); } r2, w2, err := os.Pipe(); if err != nil { fatal("%s", err); } pid, err := os.ForkExec(cmd, argv, os.Environ(), "", []*os.File{r0, w1, w2}); if err != nil { fatal("%s", err); } r0.Close(); w1.Close(); w2.Close(); c := make(chan bool); go func() { w0.Write(stdin); w0.Close(); c <- true; }(); var xstdout []byte; // TODO(rsc): delete after 6g can take address of out parameter go func() { xstdout, _ = io.ReadAll(r1); r1.Close(); c <- true; }(); stderr, _ = io.ReadAll(r2); r2.Close(); <-c; <-c; stdout = xstdout; w, err := os.Wait(pid, 0); if err != nil { fatal("%s", err); } ok = w.Exited() && w.ExitStatus() == 0; return; }
// run runs the command argv, feeding in stdin on standard input. // It returns the output to standard output and standard error. // ok indicates whether the command exited successfully. func run(stdin []byte, argv []string) (stdout, stderr []byte, ok bool) { cmd, err := exec.LookPath(argv[0]) if err != nil { fatal("exec %s: %s", argv[0], err) } r0, w0, err := os.Pipe() if err != nil { fatal("%s", err) } r1, w1, err := os.Pipe() if err != nil { fatal("%s", err) } r2, w2, err := os.Pipe() if err != nil { fatal("%s", err) } pid, err := os.ForkExec(cmd, argv, os.Environ(), "", []*os.File{r0, w1, w2}) if err != nil { fatal("%s", err) } r0.Close() w1.Close() w2.Close() c := make(chan bool) go func() { w0.Write(stdin) w0.Close() c <- true }() var xstdout []byte // TODO(rsc): delete after 6g can take address of out parameter go func() { xstdout, _ = ioutil.ReadAll(r1) r1.Close() c <- true }() stderr, _ = ioutil.ReadAll(r2) r2.Close() <-c <-c stdout = xstdout w, err := os.Wait(pid, 0) if err != nil { fatal("%s", err) } ok = w.Exited() && w.ExitStatus() == 0 return }
func exec(args []string, dir string) { p, error := os.ForkExec(args[0], args, os.Environ(), dir, []*os.File{os.Stdin, os.Stdout, os.Stderr}) if error != nil { fmt.Fprintf(os.Stderr, "Can't %s\n", error) os.Exit(1) } m, error := os.Wait(p, 0) if error != nil { fmt.Fprintf(os.Stderr, "Can't %s\n", error) os.Exit(1) } if m.WaitStatus != 0 { os.Exit(int(m.WaitStatus)) } }
// Create a FUSE FS on the specified mount point. The returned // mount point is always absolute. func mount(mountPoint string, options string) (f *os.File, finalMountPoint string, err error) { local, remote, err := unixgramSocketpair() if err != nil { return } defer local.Close() defer remote.Close() mountPoint = filepath.Clean(mountPoint) if !filepath.IsAbs(mountPoint) { cwd := "" cwd, err = os.Getwd() if err != nil { return } mountPoint = filepath.Clean(filepath.Join(cwd, mountPoint)) } cmd := []string{fusermountBinary, mountPoint} if options != "" { log.Printf("o %q", options) cmd = append(cmd, "-o") cmd = append(cmd, options) } proc, err := os.StartProcess(fusermountBinary, cmd, &os.ProcAttr{ Env: []string{"_FUSE_COMMFD=3"}, Files: []*os.File{os.Stdin, os.Stdout, os.Stderr, remote}}) if err != nil { return } w, err := os.Wait(proc.Pid, 0) if err != nil { return } if w.ExitStatus() != 0 { err = fmt.Errorf("fusermount exited with code %d\n", w.ExitStatus()) return } f, err = getConnection(local) finalMountPoint = mountPoint return }
func unmount(mountPoint string) (err os.Error) { dir, _ := filepath.Split(mountPoint) proc, err := os.StartProcess("/bin/fusermount", []string{"/bin/fusermount", "-u", mountPoint}, &os.ProcAttr{Dir: dir, Files: []*os.File{nil, nil, os.Stderr}}) if err != nil { return } w, err := os.Wait(proc.Pid, 0) if err != nil { return } if w.ExitStatus() != 0 { return os.NewError(fmt.Sprintf("fusermount -u exited with code %d\n", w.ExitStatus())) } return }
func exec(c *http.Conn, args []string) (status int) { r, w, err := os.Pipe(); if err != nil { log.Stderrf("os.Pipe(): %v\n", err); return 2; } bin := args[0]; fds := []*os.File{nil, w, w}; if *verbose { log.Stderrf("executing %v", args); } pid, err := os.ForkExec(bin, args, os.Environ(), goroot, fds); defer r.Close(); w.Close(); if err != nil { log.Stderrf("os.ForkExec(%q): %v\n", bin, err); return 2; } var buf bytes.Buffer; io.Copy(&buf, r); wait, err := os.Wait(pid, 0); if err != nil { os.Stderr.Write(buf.Bytes()); log.Stderrf("os.Wait(%d, 0): %v\n", pid, err); return 2; } status = wait.ExitStatus(); if !wait.Exited() || status > 1 { os.Stderr.Write(buf.Bytes()); log.Stderrf("executing %v failed (exit status = %d)", args, status); return; } if *verbose { os.Stderr.Write(buf.Bytes()); } if c != nil { c.SetHeader("content-type", "text/plain; charset=utf-8"); c.Write(buf.Bytes()); } return; }
func (m *Module) IsRunning() bool { //dlog.Printf("%#v %#v %#v\n", m, m.MainProcess, m.SyncProcess) waitmsg, err := os.Wait(m.MainProcess.Pid, os.WNOHANG|os.WUNTRACED) if err != nil { // TODO: When would this happen? dlog.Println("Unable to get process wait status:", err) } //dlog.Printf("%#v\n", waitmsg) // If status is not available, the pid is 0. if waitmsg.Pid == 0 { return true } if waitmsg.WaitStatus.Exited() { modules[m.Name] = nil, false return false } return true }
func build_pkg(dir string) { var args [3]string args[0] = "make" args[1] = dir + "/Makefile" args[2] = dir var fds []*os.File = new([3]*os.File) fds[0] = os.Stdin fds[1] = os.Stdout fds[2] = os.Stderr /* Replace this with git's full path, or use a shell, and then call git in the args */ pid, err := os.ForkExec("/usr/bin/make", &args, os.Envs, dir, fds) if err != nil { log.Exit(err) } os.Wait(pid, 0) }
func main() { pr, pw, _ := os.Pipe() defer pr.Close() r := bufio.NewReader(pr) w := bufio.NewWriter(os.Stdout) defer w.Flush() pid, _ := os.StartProcess("/bin/ps", []string{"ps", "-e", "-opid,ppid,comm"}, nil, "", []*os.File{nil, pw, nil}) defer os.Wait(pid, os.WNOHANG) pw.Close() child := make(map[int]*vector.IntVector) s, ok := r.ReadString('\n') // Discard the header line s, ok = r.ReadString('\n') for ok == nil { f := strings.Fields(s) if _, present := child[atoi(f[PPID])]; !present { v := new(vector.IntVector) child[atoi(f[PPID])] = v } // Save the child PIDs on a vector child[atoi(f[PPID])].Push(atoi(f[PID])) s, ok = r.ReadString('\n') } // Sort the PPIDs schild := make([]int, len(child)) i := 0 for k, _ := range child { schild[i] = k i++ } sort.SortInts(schild) // Walk throught the sorted list for _, ppid := range schild { fmt.Printf("Pid %d has %d child", ppid, child[ppid].Len()) if child[ppid].Len() == 1 { fmt.Printf(": %v\n", []int(*child[ppid])) } else { fmt.Printf("ren: %v\n", []int(*child[ppid])) } } }
func unmount(mountPoint string) (err error) { if os.Geteuid() == 0 { return privilegedUnmount(mountPoint) } dir, _ := filepath.Split(mountPoint) proc, err := os.StartProcess(fusermountBinary, []string{fusermountBinary, "-u", mountPoint}, &os.ProcAttr{Dir: dir, Files: []*os.File{nil, nil, os.Stderr}}) if err != nil { return } w, err := os.Wait(proc.Pid, 0) if err != nil { return } if w.ExitStatus() != 0 { return fmt.Errorf("fusermount -u exited with code %d\n", w.ExitStatus()) } return }
// Mount create a fuse fs on the specified mount point. The returned // mount point is always absolute. func mount(mountPoint string) (f *os.File, finalMountPoint string, err os.Error) { local, remote, err := Socketpair("unixgram") if err != nil { return } defer local.Close() defer remote.Close() mountPoint = filepath.Clean(mountPoint) if !filepath.IsAbs(mountPoint) { cwd, err := os.Getwd() if err != nil { return } mountPoint = filepath.Clean(filepath.Join(cwd, mountPoint)) } proc, err := os.StartProcess("/bin/fusermount", []string{"/bin/fusermount", mountPoint}, &os.ProcAttr{ Env: []string{"_FUSE_COMMFD=3"}, Files: []*os.File{os.Stdin, os.Stdout, os.Stderr, remote}}) if err != nil { return } w, err := os.Wait(proc.Pid, 0) if err != nil { return } if w.ExitStatus() != 0 { err = os.NewError(fmt.Sprintf("fusermount exited with code %d\n", w.ExitStatus())) return } f, err = getFuseConn(local) finalMountPoint = mountPoint return }
func TestLF(t *testing.T) { if !hasProc() { return } cx := Context{} pr, pw, err := os.Pipe() lf := []*os.File{pw} pid, err := cx.ForkExec("./test-lf.sh", lf) assert.Equal(t, nil, err) assert.T(t, pid > 0) pw.Close() line, err := ioutil.ReadAll(pr) assert.Equal(t, nil, err) assert.Equal(t, []byte{'a'}, line) w, err := os.Wait(pid, 0) assert.Equal(t, true, w.Exited()) assert.Equal(t, 0, w.ExitStatus()) }
func get_output(args []string, input []byte) (std []byte, error []byte, e os.Error) { inpr, inpw, err := os.Pipe() if err != nil { return nil, nil, err } stdr, stdw, err := os.Pipe() if err != nil { return nil, nil, err } errr, errw, err := os.Pipe() if err != nil { return nil, nil, err } pid, err := os.ForkExec(args[0], args, os.Environ(), "", []*os.File{inpr, stdw, errw}) if err != nil { return nil, nil, err } inpw.Write(input) inpw.Close() stdw.Close() errw.Close() var b bytes.Buffer io.Copy(&b, stdr) std = b.Bytes() b.Reset() io.Copy(&b, errr) error = b.Bytes() inpr.Close() stdr.Close() errr.Close() os.Wait(pid, 0) return }
// executeCommand runs the specified tool with the supplied arguments (not // including the path to the tool itself), chdir'ing to the specified directory // first. It returns true if and only if the child process returns zero. func executeCommand(tool string, args []string, dir string) bool { fmt.Printf("%s %s\n", tool, strings.Join(args, " ")) var fullArgs vector.StringVector fullArgs.Push(tool) fullArgs.AppendVector(&args) pid, err := os.ForkExec( tool, fullArgs.Data(), os.Environ(), dir, []*os.File{os.Stdin, os.Stdout, os.Stderr}) if err != nil { panic(err) } waitMsg, err := os.Wait(pid, 0) if err != nil { panic(err) } return waitMsg.ExitStatus() == 0 }
// newThread creates a new thread object and waits for its initial // signal. If cloned is true, this thread was cloned from a thread we // are already attached to. // // Must be run from the monitor thread. func (p *process) newThread(tid int, signal int, cloned bool) (*thread, os.Error) { t := &thread{tid: tid, proc: p, state: stopped} // Get the signal from the thread // TODO(austin) Thread might already be stopped if we're attaching. w, err := os.Wait(tid, syscall.WALL) if err != nil { return nil, err } if w.Pid != tid || w.StopSignal() != signal { return nil, &newThreadError{w, tid, signal} } if !cloned { err = t.ptraceSetOptions(syscall.PTRACE_O_TRACECLONE | syscall.PTRACE_O_TRACEEXIT) if err != nil { return nil, err } } p.threads[tid] = t return t, nil }
func init_mysql() { r, w, err := os.Pipe() if err != nil { panic("%v", err) } fmt.Print("Initializing DB... ") pid, _ := os.ForkExec("/usr/bin/mysql", []string{"/usr/bin/mysql", "test_db"}, os.Environ(), "/versatile", []*os.File{r, os.Stdout, os.Stderr}) // fmt.Fprintln(w,"show tables;"); fmt.Fprintln(w, "DROP TABLE personne;") fmt.Fprintln(w, "DROP TABLE cars;") fmt.Fprintln(w, "CREATE TABLE `personne` ( `id` int(11) NOT NULL auto_increment, `nom` varchar(255) default NULL, age int(3) default NULL, PRIMARY KEY (`id`) );") fmt.Fprintln(w, "INSERT INTO `personne` VALUES (1,'toto',23);") fmt.Fprintln(w, "INSERT INTO `personne` VALUES (2,'titi',NULL);") fmt.Fprintln(w, "CREATE TABLE `cars` ( `id` int(11) NOT NULL auto_increment, `plate` varchar(255) default NULL, `model` varchar(255) default NULL, owner_id int(11) default NULL, PRIMARY KEY (`id`) );") fmt.Fprintln(w, "INSERT INTO `cars` VALUES (1,'123ABC12','Renault',1);") fmt.Fprintln(w, "INSERT INTO `cars` VALUES (2,'123CBA12','Traban',1);") w.Close() os.Wait(pid, 0) fmt.Println("Finished!") conn := gouda.OpenMysql("mysql://root:@localhost:3306/test_db") gouda.GetConnectionStore().RegisterConnection(&conn) }
func main() { flag.Usage = usage flag.Parse() if *helpShort || *helpLong || flag.NArg() == 0 { flag.Usage() os.Exit(1) } fds, err := parser.ParseFiles(flag.Args(), strings.Split(*importPath, ",", -1)) if err != nil { log.Exitf("Failed parsing: %v", err) } resolver.ResolveSymbols(fds) fmt.Println("-----") proto.MarshalText(os.Stdout, fds) fmt.Println("-----") // Find plugin. pluginPath := fullPath(*pluginBinary, strings.Split(os.Getenv("PATH"), ":", -1)) if pluginPath == "" { log.Exitf("Failed finding plugin binary %q", *pluginBinary) } // Start plugin subprocess. pluginIn, meOut, err := os.Pipe() if err != nil { log.Exitf("Failed creating pipe: %v", err) } meIn, pluginOut, err := os.Pipe() if err != nil { log.Exitf("Failed creating pipe: %v", err) } pid, err := os.ForkExec(pluginPath, nil, nil, "/", []*os.File{pluginIn, pluginOut, os.Stderr}) if err != nil { log.Exitf("Failed forking plugin: %v", err) } pluginIn.Close() pluginOut.Close() // Send request. cgRequest := &plugin.CodeGeneratorRequest{ FileToGenerate: flag.Args(), // TODO: proto_file should be topologically sorted (bottom-up) ProtoFile: fds.File, } buf, err := proto.Marshal(cgRequest) if err != nil { log.Exitf("Failed marshaling CG request: %v", err) } _, err = meOut.Write(buf) if err != nil { log.Exitf("Failed writing CG request: %v", err) } meOut.Close() w, err := os.Wait(pid, 0) if err != nil { log.Exitf("Failed waiting for plugin: %v", err) } if w.ExitStatus() != 0 { log.Exitf("Plugin exited with status %d", w.ExitStatus()) } // Read response. cgResponse := new(plugin.CodeGeneratorResponse) if buf, err = ioutil.ReadAll(meIn); err != nil { log.Exitf("Failed reading CG response: %v", err) } if err = proto.Unmarshal(buf, cgResponse); err != nil { log.Exitf("Failed unmarshaling CG response: %v", err) } // TODO: check cgResponse.Error // TODO: write files for _, f := range cgResponse.File { fmt.Printf("--[ %v ]--\n", proto.GetString(f.Name)) fmt.Println(proto.GetString(f.Content)) } fmt.Println("-----") }