or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-execution.mdindex.mdprivilege-elevation.mdprocess-management.mdutilities.md

process-management.mddocs/

0

# Process Management

1

2

Comprehensive process control functionality including priority management and reliable process tree termination. Provides cross-platform process management with optional psutil integration for enhanced capabilities.

3

4

## Capabilities

5

6

### Process Priority Control

7

8

Set CPU and IO priority levels for processes to optimize system resource usage and performance characteristics.

9

10

```python { .api }

11

def set_priority(pid, priority):

12

"""

13

Set process CPU priority level.

14

15

Adjusts the CPU scheduling priority of the specified process. Uses platform-native

16

priority systems (Windows priority classes, Unix nice values) with a unified interface.

17

18

Args:

19

pid (int): Process ID to modify

20

priority (Union[int, str]): Priority level specification

21

String values (cross-platform): "verylow", "low", "normal", "high", "rt"

22

Int values (Unix only): -20 (highest) to 20 (lowest)

23

24

Raises:

25

ValueError: If priority value is invalid for the platform

26

psutil.AccessDenied: If insufficient privileges to change priority

27

psutil.NoSuchProcess: If process ID doesn't exist

28

29

Examples:

30

Set high priority for important process:

31

>>> set_priority(1234, "high")

32

33

Set background/low priority:

34

>>> set_priority(1234, "low")

35

36

Unix-specific nice value:

37

>>> set_priority(1234, -10) # Higher than normal priority

38

39

Platform Notes:

40

Windows: Uses process priority classes (IDLE, BELOW_NORMAL, NORMAL, HIGH, REALTIME)

41

Unix/Linux: Uses nice values mapped to priority strings

42

macOS: Uses nice values with BSD-style priority handling

43

"""

44

45

def set_io_priority(pid, priority):

46

"""

47

Set process IO priority level.

48

49

Controls the IO scheduling priority for disk and network operations.

50

Requires psutil module for full functionality.

51

52

Args:

53

pid (int): Process ID to modify

54

priority (str): IO priority level

55

Values: "low", "normal", "high"

56

57

Raises:

58

ValueError: If priority value is not recognized

59

psutil.AccessDenied: If insufficient privileges

60

psutil.NoSuchProcess: If process ID doesn't exist

61

NameError: If psutil module not available

62

63

Examples:

64

Set low IO priority for background tasks:

65

>>> set_io_priority(1234, "low")

66

67

Boost IO priority for time-critical operations:

68

>>> set_io_priority(1234, "high")

69

70

Platform Notes:

71

Windows: Uses IO priority classes (LOW, NORMAL, HIGH)

72

Linux: Uses ionice scheduling classes (IDLE, BEST_EFFORT, REALTIME)

73

macOS: Limited support through nice values

74

"""

75

```

76

77

### Process Tree Termination

78

79

Reliable termination of process trees including all child processes. Handles platform differences in process hierarchy and provides both soft and hard termination options.

80

81

```python { .api }

82

def kill_childs_mod(pid=None, itself=False, soft_kill=False):

83

"""

84

Kill all child processes of a given process ID.

85

86

Recursively terminates all descendant processes, handling platform differences

87

in process tree management. Provides options for graceful vs forceful termination.

88

89

Args:

90

pid (int, optional): Target process ID. If None, uses current process ID.

91

itself (bool): Whether to kill the parent process after children (default: False)

92

soft_kill (bool): Use graceful termination (SIGTERM) vs forceful (SIGKILL) (default: False)

93

94

Returns:

95

bool: True if operation completed successfully, False if target process not found

96

97

Raises:

98

OSError: If process termination fails due to system-level errors

99

100

Examples:

101

Kill all children of current process:

102

>>> kill_childs_mod()

103

104

Kill process tree including parent:

105

>>> kill_childs_mod(1234, itself=True)

106

107

Graceful shutdown of process tree:

108

>>> kill_childs_mod(1234, soft_kill=True)

109

110

Emergency cleanup on exit:

111

>>> import atexit, os

112

>>> atexit.register(kill_childs_mod, os.getpid(), True)

113

114

Platform Notes:

115

Windows: Uses process walking since Windows lacks native process trees.

116

May miss orphaned processes if parent died unexpectedly.

117

Falls back to taskkill command for stubborn processes.

118

Unix/Linux: Uses process group and parent-child relationships.

119

Supports both SIGTERM (soft) and SIGKILL (hard) signals.

120

121

Implementation Details:

122

- Prefers signal-based termination to avoid PID reuse race conditions

123

- Handles missing psutil module gracefully with reduced functionality

124

- Uses recursive termination to handle deeply nested process trees

125

- Provides fallback mechanisms for platform-specific edge cases

126

"""

127

```

128

129

## Priority Level Mappings

130

131

The priority system provides a unified interface across platforms while respecting platform-specific capabilities:

132

133

### Process Priority Levels

134

135

```python { .api }

136

# Cross-platform priority level mappings

137

PRIORITIES = {

138

"process": {

139

"verylow": ..., # Idle/background priority

140

"low": ..., # Below normal priority

141

"normal": ..., # Default system priority

142

"high": ..., # Above normal priority

143

"rt": ... # Real-time priority (use carefully)

144

},

145

"io": {

146

"low": ..., # Background IO operations

147

"normal": ..., # Standard IO priority

148

"high": ... # High-priority IO operations

149

}

150

}

151

```

152

153

### Platform-Specific Priority Constants

154

155

**Windows Priority Classes:**

156

- `IDLE_PRIORITY_CLASS`: Very low priority (verylow)

157

- `BELOW_NORMAL_PRIORITY_CLASS`: Below normal priority (low)

158

- `NORMAL_PRIORITY_CLASS`: Standard priority (normal)

159

- `HIGH_PRIORITY_CLASS`: High priority (high)

160

- `REALTIME_PRIORITY_CLASS`: Real-time priority (rt)

161

162

**Windows IO Priority Classes:**

163

- `IOPRIO_LOW`: Low IO priority

164

- `IOPRIO_NORMAL`: Normal IO priority

165

- `IOPRIO_HIGH`: High IO priority

166

167

**Unix Priority Classes:**

168

- Nice values: -20 (highest) to 20 (lowest)

169

- `IOPRIO_CLASS_IDLE`: Idle IO scheduling

170

- `IOPRIO_CLASS_BE`: Best-effort IO scheduling

171

- `IOPRIO_CLASS_RT`: Real-time IO scheduling

172

173

## Usage Patterns

174

175

### Automatic Priority Management

176

177

Command Runner can automatically set process priority during command execution:

178

179

```python

180

from command_runner import command_runner

181

182

# Run command with low priority

183

exit_code, output = command_runner(

184

'long_running_task',

185

priority='low',

186

io_priority='low'

187

)

188

```

189

190

### Manual Process Control

191

192

For more granular control, manage process priorities manually:

193

194

```python

195

import os

196

from command_runner import set_priority, set_io_priority

197

198

# Get current process ID

199

pid = os.getpid()

200

201

# Set high CPU priority for critical section

202

set_priority(pid, 'high')

203

204

# Perform critical work

205

# ...

206

207

# Reset to normal priority

208

set_priority(pid, 'normal')

209

```

210

211

### Process Tree Cleanup

212

213

Ensure reliable cleanup of spawned processes:

214

215

```python

216

import os

217

import atexit

218

from command_runner import kill_childs_mod

219

220

# Register cleanup handler

221

atexit.register(kill_childs_mod, os.getpid(), True)

222

223

# Or manual cleanup

224

def cleanup_processes():

225

kill_childs_mod(soft_kill=True) # Try graceful first

226

time.sleep(2)

227

kill_childs_mod(soft_kill=False) # Force kill if needed

228

```

229

230

## Error Handling

231

232

Process management functions provide detailed error information:

233

234

### Common Exceptions

235

- **`psutil.AccessDenied`**: Insufficient privileges for operation

236

- **`psutil.NoSuchProcess`**: Target process no longer exists

237

- **`ValueError`**: Invalid priority value or argument

238

- **`OSError`**: System-level operation failure

239

- **`NameError`**: psutil module not available (limited functionality)

240

241

### Best Practices

242

1. **Check Process Existence**: Verify process still exists before priority changes

243

2. **Handle Privileges**: Run with appropriate privileges for priority changes

244

3. **Graceful Degradation**: Handle missing psutil module gracefully

245

4. **Error Recovery**: Implement fallback strategies for failed operations

246

5. **Resource Cleanup**: Always clean up child processes to prevent resource leaks

247

248

## Dependencies

249

250

### Required

251

- Python standard library (os, subprocess, signal)

252

253

### Optional

254

- **psutil**: Enhanced process management capabilities

255

- Required for IO priority setting

256

- Required for reliable process tree termination

257

- Provides more robust priority management

258

- Installation: `pip install psutil`

259

260

### Platform-Specific

261

- **Windows**: win32process, win32api (for advanced features)

262

- **Unix/Linux**: Standard POSIX process management

263

- **macOS**: BSD-style process handling