//go:build !windows

package util

import (
	"errors"
	"syscall"
	"time"
)

// KillProcess 向进程发送 SIGTERM。
func KillProcess(pid int) error {
	return syscall.Kill(pid, syscall.SIGTERM)
}

// ForceKillProcess 向进程发送 SIGKILL。
func ForceKillProcess(pid int) error {
	return syscall.Kill(pid, syscall.SIGKILL)
}

// ProcessExists 检查进程是否存在。
func ProcessExists(pid int) bool {
	err := syscall.Kill(pid, 0)
	return err == nil || errors.Is(err, syscall.EPERM)
}

// WaitProcessExit 轮询等待进程退出。
func WaitProcessExit(pid int, timeout time.Duration) bool {
	deadline := time.Now().Add(timeout)
	for time.Now().Before(deadline) {
		if !ProcessExists(pid) {
			return true
		}
		time.Sleep(200 * time.Millisecond)
	}
	return !ProcessExists(pid)
}
