github.com/oweisse/u-root@v0.0.0-20181109060735-d005ad25fef1/cmds/kill/kill.go (about)

     1  // Copyright 2016-2017 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Kill kills processes.
     6  //
     7  // Synopsis:
     8  //     kill -l
     9  //     kill [<-s | --signal | -> <isgname|signum>] pid [pid...]
    10  //
    11  // Options:
    12  //     -l:                       list the signal names
    13  //     -name, --signal name, -s: name is the message to send. On some systems
    14  //                               this is a string, on others a number. It is
    15  //                               optional and an OS-dependent value will be
    16  //                               used if it is not set. pid is a list of at
    17  //                               least one pid.
    18  package main
    19  
    20  import (
    21  	"fmt"
    22  	"os"
    23  )
    24  
    25  const eUsage = "Usage: kill -l | kill [<-s | --signal | -> <signame|signum>] pid [pid...]"
    26  
    27  func usage() {
    28  	die(eUsage)
    29  }
    30  
    31  func die(msg string, args ...interface{}) {
    32  	fmt.Fprintf(os.Stderr, msg, args...)
    33  	fmt.Fprintf(os.Stderr, "\n")
    34  	os.Exit(1)
    35  }
    36  
    37  func main() {
    38  	op := os.Args[1]
    39  	pids := os.Args[2:]
    40  	if op[0] != '-' {
    41  		op = defaultSignal
    42  		pids = os.Args[1:]
    43  	}
    44  	// sadly, we can not use flag. Well, we could,
    45  	// it would be pretty cheap to just put in every
    46  	// possible flag as a switch, but it just gets
    47  	// messy.
    48  	//
    49  	// kill is one of the old school commands (1971)
    50  	// and arg processing was not really standard back then.
    51  	// Also, note, the -l has no meaning on Plan 9 or Harvey
    52  	// since signals on those systems are arbitrary strings.
    53  
    54  	if op[0:2] == "-l" {
    55  		if len(os.Args) > 2 {
    56  			usage()
    57  		}
    58  		fmt.Print(siglist())
    59  		os.Exit(1)
    60  	}
    61  
    62  	// N.B. Be careful if you want to change this. It has to continue to work if
    63  	// the signal is an arbitrary string. We take the path that the signal
    64  	// has to start with a -, or might be preceded by -s or --string.
    65  
    66  	if op == "-s" || op == "--signal" {
    67  		if len(os.Args) < 3 {
    68  			usage()
    69  		}
    70  		op = os.Args[2]
    71  		pids = os.Args[3:]
    72  	} else {
    73  		op = op[1:]
    74  	}
    75  
    76  	s, ok := signums[op]
    77  	if !ok {
    78  		die("%v is not a valid signal", op)
    79  	}
    80  
    81  	if len(pids) < 1 {
    82  		usage()
    83  	}
    84  	if err := kill(s, pids...); err != nil {
    85  		die("Some processes could not be killed: %v", err)
    86  	}
    87  }