Skip to content

Instantly share code, notes, and snippets.

@talebisinan
Last active August 3, 2023 14:15
Show Gist options
  • Save talebisinan/2e26c3b4493b1e9ea936249e6c064f68 to your computer and use it in GitHub Desktop.
Save talebisinan/2e26c3b4493b1e9ea936249e6c064f68 to your computer and use it in GitHub Desktop.
Kill zombie processes
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
)
const procDirectory = "/proc"
func main() {
zombiePIDs, err := findZombieProcesses()
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
if len(zombiePIDs) == 0 {
fmt.Println("No zombie processes found.")
return
}
fmt.Printf("Found %d zombie processes:\n", len(zombiePIDs))
for _, pid := range zombiePIDs {
fmt.Printf("Killing zombie process with PID %d...\n", pid)
err := killProcess(pid)
if err != nil {
fmt.Printf("Error killing process with PID %d: %v\n", pid, err)
}
}
fmt.Println("Zombie processes killed successfully.")
}
func findZombieProcesses() ([]int, error) {
var zombiePIDs []int
files, err := ioutil.ReadDir(procDirectory)
if err != nil {
return nil, err
}
for _, file := range files {
if file.IsDir() {
pid, err := strconv.Atoi(file.Name())
if err != nil {
continue // Not a process directory
}
statusFilePath := fmt.Sprintf("%s/%d/status", procDirectory, pid)
content, err := ioutil.ReadFile(statusFilePath)
if err != nil {
continue
}
if strings.Contains(string(content), "Zombie") {
zombiePIDs = append(zombiePIDs, pid)
}
}
}
return zombiePIDs, nil
}
func killProcess(pid int) error {
process, err := os.FindProcess(pid)
if err != nil {
return err
}
err = process.Kill()
if err != nil {
return err
}
return nil
}
@talebisinan
Copy link
Author

talebisinan commented Aug 3, 2023

You can run by typing go run kill_zombies.go into the terminal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment