SHARE
TWEET

Untitled

a guest Apr 22nd, 2019 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "flag"
  5.     "fmt"
  6.     "io"
  7.     "os"
  8.     "os/exec"
  9.     "path/filepath"
  10.     "time"
  11. )
  12.  
  13. func parseArgs() (string, string, []string) {
  14.     logDir := flag.String("logdir", "", "Log output directory (default=stderr)")
  15.     flag.Parse()
  16.     return *logDir, flag.Arg(0), flag.Args()[1:]
  17. }
  18.  
  19. func execution(commandName string, args[] string, stdout, stderr io.Writer) (*os.ProcessState, error){
  20.     cmd := exec.Command(commandName, args...)
  21.     childStdout, _ := cmd.StdoutPipe()
  22.     childStderr, _ := cmd.StderrPipe()
  23.  
  24.     go io.Copy(stdout, childStdout)
  25.     go io.Copy(stderr, childStderr)
  26.  
  27.     err := cmd.Run()
  28.     if err != nil {
  29.         return nil, err
  30.     }
  31.     return cmd.ProcessState, nil
  32. }
  33.  
  34. func initOut(logDir, commandName string) (stdout, stderr io.Writer, err error) {
  35.     if logDir == "" {
  36.         stdout = os.Stdout
  37.         stderr = os.Stderr
  38.     } else {
  39.         ts := time.Now().Unix()
  40.  
  41.         stdoutFileName := fmt.Sprintf("%s-%v-stdout.log", commandName, ts)
  42.         stdoutFile, err := os.Create(filepath.Join(logDir, stdoutFileName))
  43.         if err != nil {
  44.             return nil, nil, nil
  45.         }
  46.         stdout = io.MultiWriter(os.Stdout, stdoutFile)
  47.  
  48.         stderrFileName := fmt.Sprintf("%s-%v-stderr.log", commandName, ts)
  49.         stderrFile, err := os.Create(filepath.Join(logDir, stderrFileName))
  50.         if err != nil {
  51.             return nil, nil, nil
  52.         }
  53.         stderr = io.MultiWriter(os.Stderr, stderrFile)
  54.     }
  55.     return
  56. }
  57.  
  58. func main() {
  59.     logDir, commnadName, args := parseArgs()
  60.     stdout, stderr, err := initOut(logDir, commnadName)
  61.     if err != nil {
  62.         fmt.Fprintf(os.Stderr, "Can`t create file : %v\n", err)
  63.         os.Exit(1)
  64.     }
  65.  
  66.     startTime := time.Now();
  67.     ps, err := execution(commnadName, args, stdout, stderr)
  68.     if err != nil {
  69.         fmt.Fprintf(stderr, "Can`t exec command %s", commnadName)
  70.         os.Exit(1)
  71.     }
  72.     exitTime := time.Now();
  73.     fmt.Fprintln(stdout, ps.String())
  74.     fmt.Fprintf(stdout, "wall clock time=%v system time=%v user time=%v\n",
  75.         exitTime.Sub(startTime), ps.SystemTime(), ps.UserTime())
  76. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top