本文整理汇总了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
}
}
示例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")
}
}
示例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()
}
}
}
示例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)
}
}
示例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)
}
示例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)
}
示例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
}
示例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()
}
示例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)
}
}
示例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)
}
示例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, ""
}
示例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
}
示例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)
}
}
示例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)
}
示例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()
}