#!/bin/bash
# Script to pin a process and its children to CPUs 0-3 using taskset
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "Please run as root (use sudo)"
exit 1
fi
# Input: Process ID to pin
if [ -z "$1" ]; then
echo "Usage: $0 <PID>"
echo "Example: $0 1234"
exit 1
fi
PID=$1
# Validate PID
if ! ps -p "$PID" > /dev/null; then
echo "Error: PID $PID does not exist"
exit 1
fi
# Get parent and child PIDs
PIDS=$(echo "$PID"; ps -o pid --ppid "$PID" --no-headers)
# Pin all PIDs to CPUs 0-3
for pid in $PIDS; do
taskset -cp 0-3 "$pid" 2>/dev/null
if [ $? -eq 0 ]; then
echo "Pinned PID $pid to CPUs 0-3"
else
echo "Failed to pin PID $pid"
fi
done
# Verify
echo "Verifying CPU affinity:"
for pid in $PIDS; do
taskset -cp "$pid" 2>/dev/null
done