github.com/rkt/rkt@v1.30.1-0.20200224141603-171c416fac02/stage1/stop/stop.go (about) 1 // Copyright 2016 The rkt Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //+build linux 16 17 package main 18 19 import ( 20 "flag" 21 "fmt" 22 "io/ioutil" 23 "os" 24 25 "github.com/shirou/gopsutil/process" 26 ) 27 28 var ( 29 force bool 30 ) 31 32 func init() { 33 flag.BoolVar(&force, "force", false, "Forced stopping") 34 } 35 36 func readIntFromFile(path string) (i int32, err error) { 37 b, err := ioutil.ReadFile(path) 38 if err != nil { 39 return 40 } 41 _, err = fmt.Sscanf(string(b), "%d", &i) 42 return 43 } 44 45 func main() { 46 flag.Parse() 47 48 pid, err := readIntFromFile("ppid") 49 if err != nil { 50 fmt.Fprintf(os.Stderr, "error reading pid: %v\n", err) 51 os.Exit(254) 52 } 53 54 process, err := process.NewProcess(pid) 55 if err != nil { 56 fmt.Fprintf(os.Stderr, "unable to create process %d instance: %v\n", pid, err) 57 os.Exit(254) 58 } 59 60 if force { 61 children, err := process.Children() 62 if err != nil { 63 fmt.Fprintf(os.Stderr, "cannot get child processes from %d: %v\n", pid, err) 64 os.Exit(254) 65 } 66 67 for _, child := range children { 68 if err := child.Kill(); err != nil { 69 fmt.Fprintf(os.Stderr, "unable to kill process %d: %v\n", child.Pid, err) 70 os.Exit(254) 71 } 72 } 73 74 if err := process.Kill(); err != nil { 75 fmt.Fprintf(os.Stderr, "unable to kill process %d: %v\n", pid, err) 76 os.Exit(254) 77 } 78 } else { 79 if process.Terminate() != nil { 80 fmt.Fprintf(os.Stderr, "unable to terminate process %d: %v\n", pid, err) 81 os.Exit(254) 82 } 83 } 84 }