How to calculate the CPU usage of a process by PID in Linux from C?
2个答案
In Linux, calculating the CPU usage of a specific process using a C program can be achieved by reading the /proc/[pid]/stat file, where [pid] is the process ID. This file contains various statistics about the process, including CPU time fields.
Steps:
-
Open the
/proc/[pid]/statfile: First, open the/proc/[pid]/statfile in read mode, where[pid]is the process ID you want to query. -
Parse the file content: Extract the required CPU time information from this file. The main fields to focus on are
utime(the time spent by the process in user mode) andstime(the time spent in kernel mode). -
Calculate CPU usage rate: Use the total CPU time read from the
/proc/statfile to calculate the process's CPU usage rate. Record data from two time points to compute the CPU usage over that period. -
Repeat measurements: For dynamic calculation of CPU usage, repeat the above steps periodically and calculate the difference between measurements taken at two time points.
Example Code:
c#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int get_cpu_usage_pct(int pid) { char path[40], line[100]; FILE *stat_file; long long int utime, stime, total_time; sprintf(path, "/proc/%d/stat", pid); stat_file = fopen(path, "r"); if (!stat_file) { perror("Failed to open stat file"); return -1; } /* Read and parse the 14th and 15th fields (utime and stime) */ for (int i = 1; i <= 13; i++) fscanf(stat_file, "%*s"); fscanf(stat_file, "%lld %lld", &utime, &stime); fclose(stat_file); total_time = utime + stime; /* Convert to percentage in a practical application */ // This example omits the conversion to percentage because it requires system-wide CPU time information return total_time; } int main() { int pid = 1234; // Replace with actual PID printf("CPU time used by process %d: %lld\n", pid, get_cpu_usage_pct(pid)); return 0; }
Note: This example does not compute the CPU usage as a percentage because it requires reading the system's total CPU time, which is typically obtained from the /proc/stat file. In practical applications, you may need to store the values at two time points and compare the difference to calculate the CPU usage rate.