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


Golang os.FindProcess函數代碼示例

本文整理匯總了Golang中os.FindProcess函數的典型用法代碼示例。如果您正苦於以下問題:Golang FindProcess函數的具體用法?Golang FindProcess怎麽用?Golang FindProcess使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


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

示例1: waitInPIDHost

func waitInPIDHost(p *libcontainer.Process, c libcontainer.Container) func() (*os.ProcessState, error) {
	return func() (*os.ProcessState, error) {
		pid, err := p.Pid()
		if err != nil {
			return nil, err
		}

		process, err := os.FindProcess(pid)
		s, err := process.Wait()
		if err != nil {
			if err, ok := err.(*exec.ExitError); !ok {
				return s, err
			} else {
				s = err.ProcessState
			}
		}
		processes, err := c.Processes()
		if err != nil {
			return s, err
		}

		for _, pid := range processes {
			process, err := os.FindProcess(pid)
			if err != nil {
				log.Errorf("Failed to kill process: %d", pid)
				continue
			}
			process.Kill()
		}

		p.Wait()
		return s, err
	}
}
開發者ID:jorik041,項目名稱:docker,代碼行數:34,代碼來源:driver.go

示例2: TestExecDriver_KillUserPid_OnPluginReconnectFailure

func TestExecDriver_KillUserPid_OnPluginReconnectFailure(t *testing.T) {
	t.Parallel()
	ctestutils.ExecCompatible(t)
	task := &structs.Task{
		Name: "sleep",
		Config: map[string]interface{}{
			"command": "/bin/sleep",
			"args":    []string{"1000000"},
		},
		LogConfig: &structs.LogConfig{
			MaxFiles:      10,
			MaxFileSizeMB: 10,
		},
		Resources: basicResources,
	}

	driverCtx, execCtx := testDriverContexts(task)
	defer execCtx.AllocDir.Destroy()
	d := NewExecDriver(driverCtx)

	handle, err := d.Start(execCtx, task)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if handle == nil {
		t.Fatalf("missing handle")
	}
	defer handle.Kill()

	id := &execId{}
	if err := json.Unmarshal([]byte(handle.ID()), id); err != nil {
		t.Fatalf("Failed to parse handle '%s': %v", handle.ID(), err)
	}
	pluginPid := id.PluginConfig.Pid
	proc, err := os.FindProcess(pluginPid)
	if err != nil {
		t.Fatalf("can't find plugin pid: %v", pluginPid)
	}
	if err := proc.Kill(); err != nil {
		t.Fatalf("can't kill plugin pid: %v", err)
	}

	// Attempt to open
	handle2, err := d.Open(execCtx, handle.ID())
	if err == nil {
		t.Fatalf("expected error")
	}
	if handle2 != nil {
		handle2.Kill()
		t.Fatalf("expected handle2 to be nil")
	}
	// Test if the userpid is still present
	userProc, err := os.FindProcess(id.UserPid)

	err = userProc.Signal(syscall.Signal(0))

	if err == nil {
		t.Fatalf("expected user process to die")
	}
}
開發者ID:dgshep,項目名稱:nomad,代碼行數:60,代碼來源:exec_test.go

示例3: main

func main() {
	if len(os.Args) < 3 {
		fmt.Println("Usage: \n")
		fmt.Println("   process find  [PID]")
		fmt.Println("   process kill  [PID]")
		fmt.Println("   process run   [command]")
		fmt.Println("   process runLog [logPath] [command]")
		fmt.Println("   process debug [command]\n\n")
	} else {
		if os.Args[1] == "find" {
			pid, err1 := strconv.Atoi(os.Args[2])
			if err1 == nil {
				_, err2 := os.FindProcess(pid)
				if err2 == nil {
					fmt.Print(true)
					//fmt.Printf("Process %d is found", process.Pid)
				} else {
					fmt.Print(false)
				}
			} else {
				log.Fatal(false)
			}
		} else if os.Args[1] == "kill" {
			pid, err1 := strconv.Atoi(os.Args[2])
			if err1 == nil {
				process, err2 := os.FindProcess(pid)
				if err2 == nil {
					err3 := process.Kill()
					if err3 == nil {
						fmt.Print(true)
					} else {
						fmt.Print(false)
					}
				} else {
					log.Fatal(false)
				}
			} else {
				log.Fatal(false)
			}
		} else if os.Args[1] == "run" {
			cmd := exec.Command(os.Args[2], os.Args[3:]...)
			err := cmd.Start()
			if err == nil {
				if cmd.Process != nil {
					fmt.Println(cmd.Process.Pid)
				}
			} else {
				fmt.Println(err)
			}

		} else if os.Args[1] == "debug" {
			//cmd := exec.Command(os.Args[2], strings.Join(os.Args[3:], " "))
			cmd := exec.Command(os.Args[2], os.Args[3:]...)
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			cmd.Run()
		}
	}

}
開發者ID:alfhan,項目名稱:plansys,代碼行數:60,代碼來源:process.go

示例4: main

func main() {
	if os.Args[1] == "find" {
		pid, err1 := strconv.Atoi(os.Args[2])
		if err1 == nil {
			_, err2 := os.FindProcess(pid)
			if err2 == nil {
				fmt.Print(true)
				//fmt.Printf("Process %d is found", process.Pid)
			} else {
				fmt.Print(false)
			}
		} else {
			log.Fatal(false)
		}
	} else if os.Args[1] == "kill" {
		pid, err1 := strconv.Atoi(os.Args[2])
		if err1 == nil {
			process, err2 := os.FindProcess(pid)
			if err2 == nil {
				err3 := process.Kill()
				if err3 == nil {
					fmt.Print(true)
				} else {
					fmt.Print(false)
				}
			} else {
				log.Fatal(false)
			}
		} else {
			log.Fatal(false)
		}
	} else if os.Args[1] == "run" {
		cmd := exec.Command(os.Args[2], os.Args[3:]...)
		err := cmd.Start()
		if err == nil {
			if cmd.Process != nil {
				fmt.Print(cmd.Process.Pid)
			}
		} else {
			log.Fatal(err)
		}
	} else if os.Args[1] == "debug" {
		//cmd := exec.Command(os.Args[2], strings.Join(os.Args[3:], " "))
		cmd := exec.Command(os.Args[2], os.Args[3:]...)
		out, err := cmd.Output()
		//fmt.Printf("%s %s\n", os.Args[2],strings.Join(os.Args[3:], " "))
		fmt.Printf("%s\n", strings.Join(os.Args[3:], " "))
		fmt.Printf("%s\n", out)
		log.Fatal(err)
	}

}
開發者ID:balitax,項目名稱:plansys,代碼行數:52,代碼來源:process.go

示例5: stopService

//
// Stops a given command in a graceful way
//
func (am *AgentManager) stopService(cmd *exec.Cmd) {
	if cmd.Process == nil {
		return
	}

	group, _ := os.FindProcess(-1 * cmd.Process.Pid)
	group.Signal(syscall.SIGTERM)
	if cmd.Process == nil {
		return
	}

	group, _ = os.FindProcess(-1 * cmd.Process.Pid)
	group.Signal(syscall.SIGKILL)
}
開發者ID:xunmengfeng,項目名稱:patchwork,代碼行數:17,代碼來源:agents_darwin.go

示例6: TestRestartPolicyAfterRestart

func (s *DockerSuite) TestRestartPolicyAfterRestart(c *check.C) {
	testRequires(c, SameHostDaemon)

	out, _ := runSleepingContainer(c, "-d", "--restart=always")
	id := strings.TrimSpace(out)
	c.Assert(waitRun(id), check.IsNil)

	dockerCmd(c, "restart", id)

	c.Assert(waitRun(id), check.IsNil)

	pidStr := inspectField(c, id, "State.Pid")

	pid, err := strconv.Atoi(pidStr)
	c.Assert(err, check.IsNil)

	p, err := os.FindProcess(pid)
	c.Assert(err, check.IsNil)
	c.Assert(p, check.NotNil)

	err = p.Kill()
	c.Assert(err, check.IsNil)

	err = waitInspect(id, "{{.RestartCount}}", "1", 30*time.Second)
	c.Assert(err, check.IsNil)

	err = waitInspect(id, "{{.State.Status}}", "running", 30*time.Second)
	c.Assert(err, check.IsNil)
}
開發者ID:nelmediamike,項目名稱:docker,代碼行數:29,代碼來源:docker_cli_restart_test.go

示例7: Open

func (d *RktDriver) Open(ctx *ExecContext, handleID string) (DriverHandle, error) {
	// Parse the handle
	pidBytes := []byte(strings.TrimPrefix(handleID, "Rkt:"))
	qpid := &rktPID{}
	if err := json.Unmarshal(pidBytes, qpid); err != nil {
		return nil, fmt.Errorf("failed to parse Rkt handle '%s': %v", handleID, err)
	}

	// Find the process
	proc, err := os.FindProcess(qpid.Pid)
	if proc == nil || err != nil {
		return nil, fmt.Errorf("failed to find Rkt PID %d: %v", qpid.Pid, err)
	}

	// Return a driver handle
	h := &rktHandle{
		proc:   proc,
		image:  qpid.Image,
		logger: d.logger,
		doneCh: make(chan struct{}),
		waitCh: make(chan error, 1),
	}

	go h.run()
	return h, nil
}
開發者ID:rowhit,項目名稱:nomad,代碼行數:26,代碼來源:rkt.go

示例8: main

func main() {
	log.Println("Starting ...")
	defer log.Println("Shutdown complete!")
	w := worker.New(worker.Unlimited)
	defer w.Close()
	w.ErrHandler = func(e error) {
		log.Println(e)
		if e == worker.ErrConnection {
			proc, err := os.FindProcess(os.Getpid())
			if err != nil {
				log.Println(err)
			}
			if err := proc.Signal(os.Interrupt); err != nil {
				log.Println(err)
			}
		}
	}
	w.JobHandler = func(job *worker.Job) error {
		log.Printf("H=%s, UID=%s, Data=%s, DataType=%d\n", job.Handle,
			job.UniqueId, job.Data, job.DataType)
		return nil
	}
	w.AddServer("127.0.0.1:4730")
	w.AddFunc("ToUpper", ToUpper, worker.Immediately)
	w.AddFunc("ToUpperTimeOut5", ToUpperDelay10, 5)
	w.AddFunc("ToUpperTimeOut20", ToUpperDelay10, 20)
	w.AddFunc("SysInfo", worker.SysInfo, worker.Immediately)
	w.AddFunc("MemInfo", worker.MemInfo, worker.Immediately)
	go w.Work()
	sh := signal.NewHandler()
	sh.Bind(os.Interrupt, func() bool { return true })
	sh.Loop()
}
開發者ID:rale,項目名稱:gearman-go,代碼行數:33,代碼來源:worker.go

示例9: waitForFailure

// Waiting for Watch Dog to die
// Halt notify WD, kill secondary, restart WD, restard secondary.
func waitForFailure(wdChan chan int, wdSignalChan chan os.Signal, haltChan chan bool) {
	for {
		go waitForAliveFromWD(wdSignalChan, wdChan)
		<-wdChan

		fmt.Println("Primary: Watch Dog DIED!!")
		haltChan <- true

		// Open file and read PID so that we can kill secondary
		file, err := os.Open("secondaryPID")
		if err != nil {
			fmt.Println("There was an error opening the SECONDARY PID file")
			os.Exit(0)
		} else {
			reader := bufio.NewReader(file)
			val, _ := reader.ReadString('\n')
			val = strings.Trim(val, "\n")
			pid, err := strconv.Atoi(val)
			file.Close()

			if err != nil {
				fmt.Println("There was an error converting the data to an int")
			} else {

				// We got the PID for secondary
				proc, err := os.FindProcess(pid)
				if err != nil {
					fmt.Println("Error finding the process for secondary PID: ", pid, ". Error: ", err.Error())
					os.Exit(0)
				}

				// Kill secondary
				err = proc.Kill()
				if err != nil {
					fmt.Println("Error killing secondary process: ", err.Error())
					os.Exit(0)
				}
			}
		}

		// Restart WD
		wd, err := spawnWD(os.Getpid())
		if err != nil {
			fmt.Println("Error restarting Watch Dog: ", err.Error())
			os.Exit(0)
		}
		fmt.Println("Primary: Watch Dog RESTARTED")

		// Restart secondary
		_, err = spawnCopy(wd.Pid)
		if err != nil {
			fmt.Println("Error main() -> spawnCopy(): ", err.Error())
			os.Exit(0)
		}
		fmt.Println("Primary: SECONDARY RESTARTED")

		// Restart notification
		go notifyPrimaryAlive(wd, haltChan)
	}
}
開發者ID:TorChrEriksen,項目名稱:TTK4145,代碼行數:62,代碼來源:main.go

示例10: signal

func (p *nonChildProcess) signal(s os.Signal) error {
	proc, err := os.FindProcess(p.processPid)
	if err != nil {
		return err
	}
	return proc.Signal(s)
}
開發者ID:40a,項目名稱:bootkube,代碼行數:7,代碼來源:restored_process.go

示例11: killByCmd

func (self *supervisorBase) killByCmd(pid int) (bool, string) {
	pr, e := os.FindProcess(pid)
	if nil != e {
		if os.IsPermission(e) {
			e = execWithTimeout(self.killTimeout, self.stop_cmd.command(self.mode))
			if nil != e {
				return false, e.Error()
			}
			return true, ""
		}
		return false, e.Error()
	}
	defer pr.Release()

	started := time.Now()
	e = execWithTimeout(self.killTimeout, self.stop_cmd.command(self.mode))
	if nil != e {
		return false, e.Error()
	}

	used := time.Now().Sub(started)
	if used >= self.killTimeout {
		return false, fmt.Sprintf("timed out after %v", self.killTimeout)
	}

	e = waitWithTimeout(self.killTimeout-used, pr)
	if nil != e {
		return false, e.Error()
	}
	return true, ""
}
開發者ID:runner-mei,項目名稱:daemontools,代碼行數:31,代碼來源:supervisor.go

示例12: isProcessExisting

// Returns true if the specified pid points to a running process.
func isProcessExisting(pid int) bool {
	if p, err := os.FindProcess(pid); err == nil {
		defer p.Release()
		return true
	}
	return false
}
開發者ID:jkellerer,項目名稱:jenkins-client-launcher,代碼行數:8,代碼來源:runonce.go

示例13: TestFatalQuit

func TestFatalQuit(t *testing.T) {
	i := 0
	finalFunc := func() {
		i++
	}
	done := make(chan struct{})
	go func() {
		l := New(true)
		defer l.RunWhenKilled(finalFunc, 100*time.Millisecond)
		l.AddKillFunc(func() {
			done <- struct{}{}
		})
		go func() {
			l.FatalQuit()
		}()
	}()
	proc, err := os.FindProcess(os.Getpid())
	if err != nil {
		t.Fatalf("%v", err)
	}
	proc.Signal(os.Interrupt)
	<-done
	if i != 1 {
		t.Errorf("got %v, != expect 1", i)
	}
}
開發者ID:jmptrader,項目名稱:go-utils-1,代碼行數:26,代碼來源:lifecycle_test.go

示例14: tryKillingCgroupProcesses

// Scan through the whole cgroup directory and kill all processes either
// attached to the pod cgroup or to a container cgroup under the pod cgroup
func (m *podContainerManagerImpl) tryKillingCgroupProcesses(podCgroup CgroupName) error {
	pidsToKill := m.cgroupManager.Pids(podCgroup)
	// No pids charged to the terminated pod cgroup return
	if len(pidsToKill) == 0 {
		return nil
	}

	var errlist []error
	// os.Kill often errors out,
	// We try killing all the pids multiple times
	for i := 0; i < 5; i++ {
		if i != 0 {
			glog.V(3).Infof("Attempt %v failed to kill all unwanted process. Retyring", i)
		}
		errlist = []error{}
		for _, pid := range pidsToKill {
			p, err := os.FindProcess(pid)
			if err != nil {
				// Process not running anymore, do nothing
				continue
			}
			glog.V(3).Infof("Attempt to kill process with pid: %v", pid)
			if err := p.Kill(); err != nil {
				glog.V(3).Infof("failed to kill process with pid: %v", pid)
				errlist = append(errlist, err)
			}
		}
		if len(errlist) == 0 {
			glog.V(3).Infof("successfully killed all unwanted processes.")
			return nil
		}
	}
	return utilerrors.NewAggregate(errlist)
}
開發者ID:kubernetes,項目名稱:kubernetes,代碼行數:36,代碼來源:pod_container_manager_linux.go

示例15: Exit

// Exit cleans up the alloc directory, destroys cgroups and kills the user
// process
func (e *UniversalExecutor) Exit() error {
	var merr multierror.Error
	if e.cmd.Process != nil {
		proc, err := os.FindProcess(e.cmd.Process.Pid)
		if err != nil {
			e.logger.Printf("[ERROR] executor: can't find process with pid: %v, err: %v",
				e.cmd.Process.Pid, err)
		} else if err := proc.Kill(); err != nil && err.Error() != finishedErr {
			merr.Errors = append(merr.Errors,
				fmt.Errorf("can't kill process with pid: %v, err: %v", e.cmd.Process.Pid, err))
		}
	}

	if e.ctx.FSIsolation {
		if err := e.removeChrootMounts(); err != nil {
			merr.Errors = append(merr.Errors, err)
		}
	}
	if e.ctx.ResourceLimits {
		e.lock.Lock()
		if err := DestroyCgroup(e.groups); err != nil {
			merr.Errors = append(merr.Errors, err)
		}
		e.lock.Unlock()
	}
	return merr.ErrorOrNil()
}
開發者ID:stigkj,項目名稱:nomad,代碼行數:29,代碼來源:executor.go


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