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 } }
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") } }
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() } } }
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) } }
// // 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) }
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) }
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 }
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() }
// 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) } }
func (p *nonChildProcess) signal(s os.Signal) error { proc, err := os.FindProcess(p.processPid) if err != nil { return err } return proc.Signal(s) }
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, "" }
// 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 }
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) } }
// 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) }
// 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() }
// Kill will end the process identified by id func (ps *ProcessService) Kill(pid int) os.Error { p, e := os.FindProcess(pid) if e != nil { return wrapError(e) } return wrapError(p.Kill()) }
func (self *supervisorBase) killBySignal(pid int) (bool, string) { if nil == self.stop_cmd.arguments || 0 == len(self.stop_cmd.arguments) { return false, "signal is empty" } var sig os.Signal = nil switch self.stop_cmd.arguments[0] { case "kill": sig = os.Kill break case "int": sig = os.Interrupt break default: return false, "signal '" + self.stop_cmd.arguments[0] + "' is unsupported" } pr, e := os.FindProcess(pid) if nil != e { return false, e.Error() } e = pr.Signal(sig) if nil != e { return false, e.Error() } e = waitWithTimeout(self.killTimeout, pr) if nil != e { return false, e.Error() } return true, "" }
func (d *QemuDriver) Open(ctx *ExecContext, handleID string) (DriverHandle, error) { // Parse the handle pidBytes := []byte(strings.TrimPrefix(handleID, "QEMU:")) qpid := &qemuPID{} if err := json.Unmarshal(pidBytes, qpid); err != nil { return nil, fmt.Errorf("failed to parse Qemu 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 Qemu PID %d: %v", qpid.Pid, err) } // Return a driver handle h := &qemuHandle{ proc: proc, vmID: qpid.VmID, doneCh: make(chan struct{}), waitCh: make(chan error, 1), } go h.run() return h, nil }
// killProcess kills a process with the given pid func killProcess(pid int) error { proc, err := os.FindProcess(pid) if err != nil { return err } return proc.Kill() }
func notifyAlive(priPID int, ch chan bool) { halt := false priProcess, err := os.FindProcess(priPID) if err != nil { fmt.Println("There was an error finding the Primary process: ", err.Error()) return } go func() { <-ch halt = true // halt <-ch /* for term := range ch { halt = term break } */ }() for { if halt { break } time.Sleep(time.Second) priProcess.Signal(syscall.SIGILL) } }
// killCgroupProcesses freezes then iterates over all the processes inside the // manager's cgroups sending a SIGKILL to each process then waiting for them to // exit. func killCgroupProcesses(m cgroups.Manager) error { var procs []*os.Process if err := m.Freeze(configs.Frozen); err != nil { logrus.Warn(err) } pids, err := m.GetPids() if err != nil { m.Freeze(configs.Thawed) return err } for _, pid := range pids { if p, err := os.FindProcess(pid); err == nil { procs = append(procs, p) if err := p.Kill(); err != nil { logrus.Warn(err) } } } if err := m.Freeze(configs.Thawed); err != nil { logrus.Warn(err) } for _, p := range procs { if _, err := p.Wait(); err != nil { logrus.Warn(err) } } return nil }
func mainLoop(stl style) { screens := defaultScreens() displayScreen := screens[searchScreenIndex] layoutAndDrawScreen(displayScreen, stl) eventChan := make(chan termbox.Event) go readUserInput(eventChan) go sendNoneEvent(eventChan) for { event := <-eventChan //termbox.PollEvent() if event.Type == termbox.EventKey { if event.Key == termbox.KeyCtrlZ { process, _ := os.FindProcess(os.Getpid()) termbox.Close() process.Signal(syscall.SIGSTOP) termbox.Init() } newScreenIndex := displayScreen.handleKeyEvent(event) if newScreenIndex < len(screens) { displayScreen = screens[newScreenIndex] layoutAndDrawScreen(displayScreen, stl) } else { break } } if event.Type == termbox.EventResize || event.Type == termbox.EventNone { layoutAndDrawScreen(displayScreen, stl) } } }
func (s *S) TestStop(c *C) { var server testserver.TestServer server.SetPath(c.MkDir()) defer server.Stop() // Server should not be running. process := server.ProcessTest() c.Assert(process, IsNil) session := server.Session() addr := session.LiveServers()[0] session.Close() // Server should be running now. process = server.ProcessTest() p, err := os.FindProcess(process.Pid) c.Assert(err, IsNil) p.Release() server.Stop() // Server should not be running anymore. session, err = mgo.DialWithTimeout(addr, 500*time.Millisecond) if session != nil { session.Close() c.Fatalf("Stop did not stop the server") } }
func TestServerState_StateShutdown(t *testing.T) { done := make(chan struct{}) started := make(chan struct{}) origServerState := miyabi.ServerState miyabi.ServerState = func(state miyabi.State) { switch state { case miyabi.StateStart: started <- struct{}{} case miyabi.StateShutdown: done <- struct{}{} } } defer func() { miyabi.ServerState = origServerState }() go miyabi.ListenAndServe(addr, nil) select { case <-started: pid := os.Getpid() p, err := os.FindProcess(pid) if err != nil { t.Fatal(err) } if err := p.Signal(miyabi.ShutdownSignal); err != nil { t.Fatal(err) } case <-time.After(5 * time.Second): t.Errorf("timeout") } select { case <-done: case <-time.After(5 * time.Second): t.Errorf("timeout") } }
// Lock creates a lockfile which prevents to open more than one instance // of the same node (on the same machine). func (ctx *Context) Lock() (err error) { var f *os.File var p *os.Process var pid int lockFile := path.Join(ctx.storageDir, ctx.nodeName+".lock") if f, err = os.Open(lockFile); err != nil { goto lock } if _, err = fmt.Fscanf(f, "%d", &pid); err != nil && pid == 0 { goto lock } if p, err = os.FindProcess(pid); err == nil && p != nil { if err = p.Signal(os.UnixSignal(0)); err == nil { return errors.New( fmt.Sprintf("node '%s' is already running", ctx.NodeName())) } } lock: // Write a lock file. if f, err = os.Create(lockFile); err == nil { pid := os.Getppid() f.Write([]byte(fmt.Sprintf("%d", pid))) f.Close() } return nil }
func (p *Process) Signal(signal syscall.Signal) error { group, err := os.FindProcess(-1 * p.Process.Pid) if err == nil { err = group.Signal(signal) } return err }
func killCgroupProcs(c libcontainer.Container) { var procs []*os.Process if err := c.Pause(); err != nil { logrus.Warn(err) } pids, err := c.Processes() if err != nil { // don't care about childs if we can't get them, this is mostly because cgroup already deleted logrus.Warnf("Failed to get processes from container %s: %v", c.ID(), err) } for _, pid := range pids { if p, err := os.FindProcess(pid); err == nil { procs = append(procs, p) if err := p.Kill(); err != nil { logrus.Warn(err) } } } if err := c.Resume(); err != nil { logrus.Warn(err) } for _, p := range procs { if _, err := p.Wait(); err != nil { logrus.Warn(err) } } }
// IsAlive will check if the process is alive or not. // Returns true if the process is alive or false otherwise. func (proc *Proc) IsAlive() bool { p, err := os.FindProcess(proc.Pid) if err != nil { return false } return p.Signal(syscall.Signal(0)) == nil }
// execSetns runs the process that executes C code to perform the setns calls // because setns support requires the C process to fork off a child and perform the setns // before the go runtime boots, we wait on the process to die and receive the child's pid // over the provided pipe. func (p *setnsProcess) execSetns() error { err := p.cmd.Start() p.childPipe.Close() if err != nil { return newSystemError(err) } status, err := p.cmd.Process.Wait() if err != nil { p.cmd.Wait() return newSystemError(err) } if !status.Success() { p.cmd.Wait() return newSystemError(&exec.ExitError{ProcessState: status}) } var pid *pid if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil { p.cmd.Wait() return newSystemError(err) } process, err := os.FindProcess(pid.Pid) if err != nil { return err } p.cmd.Process = process return nil }
func main() { myarg := os.Args[1] if myarg == "start" { mypid := os.Getpid() thepid := strconv.Itoa(mypid) d1 := []byte(thepid) err := ioutil.WriteFile(pid_file, d1, 0644) check(err) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, html_file) }) //log.Printf("Listening...") http.ListenAndServe(":3000", nil) } if myarg == "stop" { dat, err := ioutil.ReadFile(pid_file) check(err) pid_str := fmt.Sprintf("%s", string(dat)) pid, err := strconv.Atoi(pid_str) check(err) p, err := os.FindProcess(pid) check(err) er := p.Kill() check(er) } }