Darwin / OSXでプログラムでプロセス情報を決定する
-
03-07-2019 - |
質問
次のメンバー関数を持つクラスがあります:
/// caller pid
virtual pid_t Pid() const = 0;
/// physical memory size in KB
virtual uint64_t Size() const = 0;
/// resident memory for this process
virtual uint64_t Rss() const = 0;
/// cpu used by this process
virtual double PercentCpu() const = 0;
/// memory used by this process
virtual double PercentMemory() const = 0;
/// number of threads in this process
virtual int32_t Lwps() const = 0;
このクラスの義務は、呼び出し元に関するプロセス情報を返すことです。物理メモリサイズはsysctl呼び出しで簡単に決定でき、pidは簡単ですが、psまたはtopでpopenを呼び出し、出力を解析することを除いて、残りの呼び出しは私を避けました。これは受け入れられません。どんな助けも大歓迎です。
要件:
g ++ 4.0でコンパイル
obj-cなし
OSX 10.5
解決
プロセス情報は pidinfo
から取得されます。
cristi:~ diciu$ grep proc_pidinfo /usr/include/libproc.h
int proc_pidinfo(int pid, int flavor, uint64_t arg, void *buffer, int buffersize);
cpu負荷は host_statistics
から取得されます。
cristi:~ diciu$ grep -r host_statistics /usr/include/
/usr/include/mach/host_info.h:/* host_statistics() */
/usr/include/mach/mach_host.defs:routine host_statistics(
/usr/include/mach/mach_host.h:/* Routine host_statistics */
/usr/include/mach/mach_host.h:kern_return_t host_statistics
詳細については、 top
および lsof
のソースを確認してください。これらはオープンソースです(Apple開発者として登録する必要がありますが、無料です)。
https://opensource.apple .com / source / top / top-111.20.1 / libtop.c.auto.html
後の編集:これらのインターフェースはすべてバージョン固有であるため、実動コード(libproc.h)を作成する際にはそれを考慮する必要があります。
/*
* This header file contains private interfaces to obtain process information.
* These interfaces are subject to change in future releases.
*/
他のヒント
Objective-Cとは言わないので、ほとんどのMacOSフレームワークを除外します。
getrusage()を使用してCPU時間を取得できます。getrusage()は、ユーザーとシステムのCPU時間の合計をプロセスに請求します。 CPUの割合を取得するには、getrusageの値を1秒に1回(または粒度に合わせて)スナップショットする必要があります。
#include <sys/resource.h>
struct rusage r_usage;
if (getrusage(RUSAGE_SELF, &r_usage)) {
/* ... error handling ... */
}
printf("Total User CPU = %ld.%ld\n",
r_usage.ru_utime.tv_sec,
r_usage.ru_utime.tv_usec);
printf("Total System CPU = %ld.%ld\n",
r_usage.ru_stime.tv_sec,
r_usage.ru_stime.tv_usec);
getrusage構造にはRSSフィールドがありますが、MacOS X 10.5では常にゼロであるように見えます。 マイケルナイトがブログを書きましたRSSの決定方法については数年前に投稿してください。
これらの値のほとんどはMach APIで利用できると思いますが、私がそこを突っついてからしばらく経ちました。または、「ps」のソースコードを見るだけでもかまいません。または&quot; top&quot;コマンドを実行し、それらの実行方法を確認します。
次のコードをMac OSのプロセス情報に使用できます。
void IsInBSDProcessList(char *name) {
assert( name != NULL);
kinfo_proc *result;
size_t count = 0;
result = (kinfo_proc *)malloc(sizeof(kinfo_proc));
if(GetBSDProcessList(&result,&count) == 0) {
for (int i = 0; i < count; i++) {
kinfo_proc *proc = NULL;
proc = &result[i];
}
}
free(result);
}
kinfo_proc構造体には、プロセス識別子(pid)などのプロセスに関するすべての情報が含まれます。 プロセスグループ、プロセスステータスなど