Metadata-Version: 2.3
Name: kill-process-tree
Version: 0.1.0
Summary: A Python utility to gracefully terminate a process and all its child processes
Author: Zhiming Ma
Author-email: Zhiming Ma <codes.icy@gmail.com>
Requires-Dist: psutil
Requires-Dist: pytest ; extra == 'test'
Requires-Python: >=3.12
Provides-Extra: test
Description-Content-Type: text/markdown

# kill-process-tree

A Python utility to gracefully terminate a process and all its child processes (the process tree).

## Features

- **Recursive termination**: Kills a parent process and all its descendants
- **Graceful shutdown**: Attempts to terminate processes cleanly before force-killing
- **Error handling**: Handles edge cases like already-exited processes and permission issues
- **Configurable logging**: Enable debug logs via environment variable

## Installation

Install from the repository:

```bash
pip install .
```

Or using `uv`:

```bash
uv pip install .
```

## Usage

### As a Python module

Run the package directly from the command line:

```bash
python3 -m kill_process_tree 1234
```

To see help:

```bash
python3 -m kill_process_tree --help
```

### As a Python function

```python
from kill_process_tree import kill_process_tree

# Kill process with PID 1234 and all its children
kill_process_tree(1234)
```

### Debugging with Logs

Enable debug logging to see detailed information about the termination process:

```bash
KILL_PROCESS_TREE_LOG=DEBUG python3 -m kill_process_tree 1234
```

### Log Levels

Control the logging level with the `KILL_PROCESS_TREE_LOG` environment variable:

```bash
KILL_PROCESS_TREE_LOG=DEBUG python3 -m kill_process_tree 1234
```

If the environment variable is not set, logging is disabled by default.

## How It Works

1. **Snapshot children**: Gets a snapshot of all child processes recursively
2. **Terminate children first**: Sends `SIGTERM` to all child processes (in reverse order)
3. **Wait for graceful shutdown**: Waits up to 3 seconds for processes to exit cleanly
4. **Force-kill stubborn processes**: Sends `SIGKILL` to any processes that didn't exit
5. **Terminate parent**: Finally terminates (and if needed, kills) the parent process

## Error Handling

The function gracefully handles:
- Processes that disappear before they can be terminated
- Access denied errors when lacking permissions
- Timeout errors during graceful shutdown

## Requirements

- Python 3.12+
- `psutil` library
