github.com/rkt/rkt@v1.30.1-0.20200224141603-171c416fac02/stage1_fly/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 "syscall" 25 ) 26 27 var ( 28 force bool 29 ) 30 31 func init() { 32 flag.BoolVar(&force, "force", false, "Forced stopping") 33 } 34 35 func readIntFromFile(path string) (i int, err error) { 36 b, err := ioutil.ReadFile(path) 37 if err != nil { 38 return 39 } 40 _, err = fmt.Sscanf(string(b), "%d", &i) 41 return 42 } 43 44 func main() { 45 flag.Parse() 46 var sig syscall.Signal 47 48 if force { 49 sig = syscall.SIGKILL 50 } else { 51 sig = syscall.SIGTERM 52 } 53 54 pid, err := readIntFromFile("pid") 55 if err != nil { 56 fmt.Fprintf(os.Stderr, "error reading pid: %v\n", err) 57 os.Exit(254) 58 } 59 60 // check for process existence, then kill the process otherwise the group 61 err = syscall.Kill(pid, syscall.Signal(0)) 62 if err == nil { 63 err = syscall.Kill(pid, sig) 64 if err != nil { 65 fmt.Fprintf(os.Stderr, "error stopping process %d: %v\n", pid, err) 66 os.Exit(254) 67 } 68 } else { 69 pgid, err := readIntFromFile("pgid") 70 if err != nil { 71 fmt.Fprintf(os.Stderr, "error reading pgid: %v\n", err) 72 os.Exit(254) 73 } 74 err = syscall.Kill(-pgid, sig) 75 if err != nil { 76 fmt.Fprintf(os.Stderr, "error stopping process group %d: %v\n", pgid, err) 77 os.Exit(254) 78 } 79 } 80 }