如何查看占用CPU的PID关联的R及Postgres查询或脚本?
Got it, let's break this down for both Postgres and R processes since they're the two culprits hogging your CPU. Here's how you can track down exactly what's running under those high-PID processes:
针对PostgreSQL进程
Postgres has built-in tools to directly map PIDs to running queries—this is the easiest way to get to the root of the CPU usage:
- First, take the high-CPU PID you found via
top, then run this query in a Postgres shell (likepsql):
The pg_stat_activity system view will spit out the full query text, when it started, which user/database it's tied to, and even its current state (e.g., running, waiting for a lock). This is usually all you need to identify a resource-heavy query.SELECT pid, query_start, query, state, usename, datname FROM pg_stat_activity WHERE pid = <YOUR_POSTGRES_PID>; - If you want real-time monitoring without switching to
psql, install and usepg_top—it's a Postgres-specific version oftopthat shows each Postgres process alongside its active query. - For a quick sanity check, you can also use
psto see basic process context:
This won't show the query, but it'll tell you things like the connected database and user, which can help narrow down where to look next.ps aux | grep <YOUR_POSTGRES_PID>
针对R进程
R processes are a bit different, but you can still get clear visibility into what they're running:
- Start with the
pscommand to get the full command line that launched the R process:
If the R process is running a script (e.g.,ps -f -p <YOUR_R_PID>Rscript analysis.R), this will show you the exact script path right away. - If the
psoutput gets truncated (common with long command lines), pull the full command from the proc filesystem:
Thecat /proc/<YOUR_R_PID>/cmdline | tr '\0' ' '/procdirectory stores raw process info, andtr '\0' ' 'converts the null-separated command line into readable text. - If the R process is an interactive session (someone running R in a terminal), use
lsofto find which terminal it's attached to:
Look for lines withlsof -p <YOUR_R_PID> | grep pts/dev/pts/X—you can switch to that terminal (if you have permissions) to see what the user is executing. - For deeper debugging,
stracecan track system calls made by the R process to see which operations are eating CPU:
Thestrace -p <YOUR_R_PID> -c-cflag gives a summary of system call counts and time spent, so you can spot if the R process is stuck on file I/O, computation, or something else.
总的来说,Postgres用pg_stat_activity最直接高效,R用ps和proc文件系统就能拿到大部分关键信息。如果遇到权限问题,记得用sudo或者切换到对应的进程用户来执行命令。
内容的提问来源于stack exchange,提问作者iskandarblue
相关产品推荐
相关产品推荐

