1

在 Solaris 10 和 C 中,我想定期查询像

  • 该操作系统进程中特定 LWP 的 CPU 使用率。
  • 该操作系统进程的内存使用情况。

我已经知道如何通过打开 /proc/pid/psinfo 并从中读取 (pr_rssize) 来执行后者,但是有没有办法实现前者?

过去,我分叉了一份 prstat,解析了输出并将其读回我的 C 代码中。当我希望查询越来越多的此类信息时,这变得越来越乏味,而且感觉很明显是错误的。当然有一种方法可以用一些简单的 C 代码来做到这一点。

谢谢你的帮助。尼克B

4

3 回答 3

2

ps在 Solaris 上,可以通过读取/proc/pid /lwp/lwpid来获取lwp 特定的信息/lwpsinfo。该文件包含一个lwpsinfo结构,其中包括:

timestruc_t pr_time;      /* cpu time for this lwp */

有关更多详细信息,请参见proc(4)

于 2009-08-13T13:36:31.570 回答
1

当您要求 C 解决方案时,也许您可​​以查看 perl 模块Solaris::Procfs以了解它在提取信息方面做了什么?

于 2009-08-13T09:59:29.823 回答
1

#include <stdio.h>
#include <dirent.h>
#include <procfs.h>

int psinfo_thread_info(pid_t pid)
{
    int i, nent, nread = 0;
    size_t entsz;

    FILE *fp = NULL;
    char file_name[128] = {0,};
    char *ptr, *buf;
    prheader_t  header;
    lwpsinfo_t *lwpsinfo;

    snprintf(file_name, sizeof(file_name), "/proc/%ld/lpsinfo", pid);
    if ((fp = fopen(file_name, "r")) == NULL) {
        return -1;
    }

    nread = fread(&header, sizeof(prheader_t), 1, fp);
    if (nread < 0) {
        fclose(fp);
        return -1;
    }

    nent = header.pr_nent;
    printf("  Thread_num: %d\n", nent);

    entsz = header.pr_entsize * nent;
    ptr = buf = malloc(entsz);
    if (pread(fileno(fp), buf, entsz, sizeof (struct prheader)) != entsz) {
        free(ptr);
        free(buf);
        fclose(fp);
        return -1;
    }
    fclose(fp);

    for (i = 0; i < nent; i++, ptr += header.pr_entsize)
    {
        lwpsinfo = (lwpsinfo_t *)ptr;
        if (lwpsinfo == NULL) {
            continue;
        }
        printf("[%2d thread] cpu_usage = %.2lf%%\n",
                lwpsinfo->pr_lwpid,
                ((double)(lwpsinfo->pr_pctcpu * 100.0) / 0x8000));
    }
    free(ptr);
    free(buf);
    return 0;
}

int main(void)
{
    FILE *fp = NULL;
    DIR *proc_dir = NULL;
    struct dirent *dir_entry = NULL;
    int nread = 0;
    char file_name[128] = {0,};
    psinfo_t pinfo;

    if ((proc_dir = opendir("/proc")) == NULL) {
        printf("opendir failed\n");
        return -1;
    }

    while ((dir_entry = readdir(proc_dir)) != NULL)
    {
        if (atoi(dir_entry->d_name) == 0) {
            continue;
        }
        snprintf(file_name, sizeof(file_name), "/proc/%s/psinfo",
                dir_entry->d_name);

        if ((fp = fopen(file_name, "r")) == NULL) {
            continue;
        }

        nread = fread(&pinfo, sizeof(pinfo), 1, fp);
        if (nread < 0) {
            fclose(fp);
            continue;
        }
        fclose(fp);

        printf("---------------------------\n");
        printf("\nPROC:%s PID:%ld, CPU_USAGE:%.2lf%% ",
                pinfo.pr_fname, pinfo.pr_pid,
                ((double)(pinfo.pr_pctcpu * 100.0) / 0x8000));

        psinfo_thread_info(pinfo.pr_pid);
    }
    closedir(proc_dir);

    return 0;
}

于 2016-01-07T01:57:59.307 回答