Video Coming Soon...

Created by Zed A. Shaw Updated 2025-10-23 14:49:14

42: nohup

This exercise is pending. Quick notes about this exercise:

The Code

View Source file go-coreutils/nohup/main.go Only

package main

import (
  "os"
  "os/exec"
  "github.com/mattn/go-isatty"
  "flag"
  "log"
  "io"
  "os/signal"
  "syscall"
)

func Exec(prog string, args []string, target_out io.Writer) {
    cmd := exec.Command(prog, args...)
    if cmd.Err != nil { log.Fatal(cmd.Err) }

    in, err := cmd.StdinPipe()
    if err != nil { log.Fatal(err) }
    in.Close()

    stdout, err := cmd.StdoutPipe()
    if err != nil { log.Fatal(err) }

    stderr, err := cmd.StderrPipe()
    if err != nil { log.Fatal(err) }

    output := io.MultiReader(stdout, stderr)

    err = cmd.Start()
    if err != nil { log.Fatal(err) }

    _, err = io.Copy(target_out, output)
    if err != nil { log.Fatal(err) }
}

func OpenOutput() io.Writer {
  fd := os.Stdout.Fd()
  is_atty := isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd)

  if is_atty {
    // create nohup
    out_file, err := os.OpenFile("nohup.out", os.O_RDWR | os.O_CREATE | os.O_TRUNC, 0644)
    if err != nil { log.Fatal(err) }
    return out_file
  } else {
    return os.Stdout
  }
}

func main() {
  flag.Parse()
  args := flag.Args()

  if flag.NArg() == 0 {
      log.Fatal("USAGE: nohup cmd [args]")
  }

  output := OpenOutput()
  Exec(args[0], args[1:], output)

  signal.Ignore(syscall.SIGHUP)
}
Previous Lesson Next Lesson

Register for Learn Go the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.