Last active
August 3, 2023 14:15
-
-
Save talebisinan/2e26c3b4493b1e9ea936249e6c064f68 to your computer and use it in GitHub Desktop.
Kill zombie processes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can run by typing
go run kill_zombies.go
into the terminal.