Attach perf to a Running PID Without Restarting the Service
perf record -p [pid] attaches to an already-running process, arming per-task events without any restart or code change. The kernel installs the performance counters against the task's context so samples are only taken while that task is on-CPU, which is far more efficient than system-wide capture when you already know the suspect. perf respects the process's thread group, and with --inherit it follows children, so forked worker pools are captured too. The resulting perf.data is self-contained and can be analyzed offline with perf report or perf script.
This is the standard approach in production incident response: you get a paged at 3 AM, SSH into the box, attach perf to the hot PID for 30 seconds, and have a call-graph profile before the service is restarted. It is also the right tool for profiling long-lived daemons where a restart would drop connections, or for capturing a JIT-heavy workload after warmup when the interesting code is already compiled.
Be aware that attaching to a process running under a different UID requires CAP_SYS_ADMIN or CAP_PERFMON, and many hardened distros set kernel.perf_event_paranoid to 2 or 3, which blocks unprivileged attach entirely. Overhead scales with frequency and call-graph mode: DWARF unwinding is expensive because it parses .eh_frame at each sample, so prefer frame-pointer unwinding when the binary supports it. A common pitfall is profiling a process that is actually blocked on I/O, which yields almost no samples and misleads you into thinking the code is fine.
> System.Execute()
PID=$(pgrep -n myapp)
perf record -F 99 -g -p "$PID" --call-graph fp -o /tmp/pid.data -- sleep 30
perf report -i /tmp/pid.data --stdio --sort=dso,symbol | head -60
> Architecture & Security Context
Verified for Valters IT Hub. When deploying this configuration in a production homelab or enterprise environment, ensure that you monitor system resources and implement strict access controls. Administrator privileges are required.
ID: VALTERSIT-8E09F02FA0F1