I invented a couple of utilities at work today. They’re really useful little go programs. So useful, in fact, that they have already existed for many years. I haven’t written in a while so I figured I’d post them here as a little guessing game. See if you can figure out what they are from the code, just note that they are not faithful reimplementations, as I didn’t originally set out to reimplement anything. Expand the description for a hint.

#1

{
        ctx, _ := context.WithTimeout(context.Background(), timeout)
        cmd := exec.CommandContext(ctx, os.Args[1], os.Args[2:]...)
        cmd.Stdout, cmd.Stderr, cmd.Stdin = os.Stdout, os.Stderr, os.Stdin
        var err error
        if err = cmd.Start(); err != nil {
                fmt.Fprintln(os.Stderr, err)
        } else {
                err = cmd.Wait()
        }
        os.Exit(exitCode(err))
}

description

solution

#2

{
	cmd := exec.Command(os.Args[1], os.Args[2:]...)
	cmd.Stdout, cmd.Stderr, cmd.Stdin = os.Stdout, os.Stderr, os.Stdin
	var err error
	start := time.Now()
	if err = cmd.Start(); err != nil {
		fmt.Fprintln(os.Stderr, err)
	} else {
		err = cmd.Wait()
	}
	end := time.Now()
	var rusage syscall.Rusage
	syscall.Getrusage(syscall.RUSAGE_CHILDREN, &rusage)
	fmt.Printf("rss:%d user:%s sys:%s real:%s\n", rusage.Maxrss, time.Duration(rusage.Utime.Nano())*time.Nanosecond, time.Duration(rusage.Stime.Nano())*time.Nanosecond, end.Sub(start))
	os.Exit(exitCode(err))
}

description

solution

#3

{
       var rlimit syscall.Rlimit
       rlimit.Cur = 134217728
       rlimit.Max = 134217728
       syscall.Setrlimit(syscall.RLIMIT_AS, &rlimit)
       cmd := exec.Command(os.Args[1], os.Args[2:]...)
       cmd.Stdout, cmd.Stderr, cmd.Stdin = os.Stdout, os.Stderr, os.Stdin
       var err error
       if err = cmd.Start(); err != nil {
               fmt.Fprintln(os.Stderr, err)
       } else {
               err = cmd.Wait()
       }
       os.Exit(exitCode(err))
}

description

solution

If you like this kind of thing, many other utilities can be found in go-coreutils.