Skip to content

Instantly share code, notes, and snippets.

@brandt
Created October 19, 2016 19:42
Show Gist options
  • Save brandt/ac97a743cab2b10e94c8662e804b24f5 to your computer and use it in GitHub Desktop.
Save brandt/ac97a743cab2b10e94c8662e804b24f5 to your computer and use it in GitHub Desktop.
Program demonstrating the difference between zombie and orphan processes
// Program demonstrating the difference between zombie and orphan processes.
//
// BUILDING
//
// go build procdemo.go
//
// USAGE
//
// procdemo zombie
// procdemo orphan
//
// AUTHOR
//
// - J. Brandt Buckley <brandt@runlevel1.com>
//
package main
import (
"fmt"
"os"
"os/exec"
"time"
)
// zombie executes a command and never checks its exit status.
//
// The sleep process will exit, but will still appear in the process table
// as a zombie until the we exit.
func zombie() {
cmd := exec.Command("true")
cmd.Start()
fmt.Printf("Check out the zombie with:\n\n ps -lfp %d\n\n", cmd.Process.Pid)
fmt.Println("Process will remain in the process table until we quit (in 10 min).")
// Don't exit for a long time so that the zombie sticks around.
time.Sleep(600 * time.Second)
}
// orphan executes a sleep command and then kills itself.
//
// The sleep process will still be running, but init will become its parent.
func orphan() {
cmd := exec.Command("sleep", "600")
cmd.Start()
fmt.Printf("Check out the orphan with:\n\n ps -lfp %d\n\n", cmd.Process.Pid)
fmt.Println("We're going terminate abruptly, but it will continue running until finished (10 min).")
// Shoot self in the head
exec.Command("kill", "-9", string(os.Getpid())).Start()
// NOTE: We're not using the syscall package so this can be cross-compiled.
}
func usage() {
fmt.Printf("Usage: %s <zombie|orphan>\n", os.Args[0])
}
func main() {
if len(os.Args) < 2 {
fmt.Println("Argument required.")
usage()
os.Exit(2)
}
switch os.Args[1] {
case "zombie":
zombie()
case "orphan":
orphan()
case "help", "-h", "--help":
usage()
default:
fmt.Println("Invalid command.")
usage()
os.Exit(2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment