![](/img/trans.png)
[英]How do I set the command line arguments in a C program so that it's visible when users type “ps aux”?
[英]"ps aux" command in C
對於學校項目,我需要用 C 重新編程ps aux
命令(如下圖):
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 168028 12052 ? Ss 06:20 0:07 /sbin/init splash
root 2 0.0 0.0 0 0 ? S 06:20 0:00 [kthreadd]
root 3 0.0 0.0 0 0 ? I< 06:20 0:00 [rcu_gp]
root 4 0.0 0.0 0 0 ? I< 06:20 0:00 [rcu_par_gp]
root 6 0.0 0.0 0 0 ? I< 06:20 0:00 [kworker/0:0H-kblockd]
root 9 0.0 0.0 0 0 ? I< 06:20 0:00 [mm_percpu_wq]
root 10 0.0 0.0 0 0 ? S 06:20 0:00 [ksoftirqd/0]
root 11 0.0 0.0 0 0 ? I 06:20 0:03 [rcu_sched]
root 12 0.0 0.0 0 0 ? S 06:20 0:00 [migration/0]
root 13 0.0 0.0 0 0 ? S 06:20 0:00 [idle_inject/0]
root 14 0.0 0.0 0 0 ? S 06:20 0:00 [cpuhp/0]
root 15 0.0 0.0 0 0 ? S 06:20 0:00 [cpuhp/1]
root 16 0.0 0.0 0 0 ? S 06:20 0:00 [idle_inject/1]
root 17 0.0 0.0 0 0 ? S 06:20 0:00 [migration/1]
root 18 0.0 0.0 0 0 ? S 06:20 0:00 [ksoftirqd/1]
root 20 0.0 0.0 0 0 ? I< 06:20 0:00 [kworker/1:0H-kblockd]
root 21 0.0 0.0 0 0 ? S 06:20 0:00 [cpuhp/2]
root 22 0.0 0.0 0 0 ? S 06:20 0:00 [idle_inject/2]
root 23 0.0 0.0 0 0 ? S 06:20 0:00 [migration/2]
root 24 0.0 0.0 0 0 ? S 06:20 0:00 [ksoftirqd/2]
我設法重新編程了除%CPU和%MEM之外的所有列。 和另一個一樣,我知道我的答案在/proc//[stat|status] 中,但我不知道我需要取什么值以及計算百分比的公式是什么。
任何的想法 ?
您顯示的內容取決於您模仿的ps
命令。
BSD ps
手冊頁是關於 %CPU 的:
進程的CPU利用率; 這是前一(實際)時間最多一分鍾的衰減平均值。 由於計算時基的時間不同(某些進程可能非常年輕),所有 %cpu 字段的總和可能會超過 100%。
%mem 的描述是這樣的:
此進程使用的實際內存百分比。
請注意,它說的是“真實”內存,我認為這意味着計算中不包括虛擬內存。
查看ps
命令的源碼。
在下面的:
[...]
#define cook_etime(P) (((unsigned long long)seconds_since_boot >= (P->start_time / Hertz)) ? ((unsigned long long)seconds_since_boot - (P->start_time / Hertz)) : 0)
[...]
Hertz = sysconf(_SC_CLK_TCK);
[...]
/* jiffies used by this process */
total_time = pp->utime + pp->stime;
if(include_dead_children) total_time += (pp->cutime + pp->cstime);
/* seconds of process life */
seconds = cook_etime(pp);
/* scaled %cpu, 999 means 99.9% */
if(seconds) pcpu = (total_time * 1000ULL / Hertz) / seconds;
if (pcpu > 999U)
return snprintf(outbuf, COLWID, "%u", pcpu/10U);
return snprintf(outbuf, COLWID, "%u.%u", pcpu/10U, pcpu%10U);
[...]
在下面的:
/* pp->vm_rss * 1000 would overflow on 32-bit systems with 64 GB memory */
pmem = pp->vm_rss * 1000ULL / kb_main_total;
if (pmem > 999) pmem = 999;
snprintf(outbuf, COLWID, "%2u.%u", (unsigned)(pmem/10), (unsigned)(pmem%10));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.