gpt4 book ai didi

c++ - 使用 procf//status 了解进程状态

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:28 27 4
gpt4 key购买 nike

我正在研究 Solaris。

我知道如果有一个进程在运行,就会有一个名为 /proc/<PID>/status 的文件, 其中<PID>是进程 ID,它包含一个名为 state 的字段.

例如,我使用了我的 shell 进程:

> ps
PID TTY TIME CMD
18671 0:01 tcsh

其进程ID为18671。

我编写了一个简单的 C 程序来提取该信息:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/procfs.h>
#include <sys/fcntl.h>

static void get_status (pid_t pid)
{
char procpath[100];
char buf[100];
int pfd;
char State[100];
char Name[100];
prstatus_t * pms;
FILE *proc;


sprintf(procpath, "/proc/%d/status", pid);

proc = fopen(procpath,"r");
if (proc) {
printf("Open Successful\n");
fgets(buf,256,proc); sscanf(buf,"Name:\t%s",Name);
fgets(buf,256,proc); sscanf(buf,"State:\t%c",State);
}
printf("%s",Name);
printf("%s",State);
}

int main(int argc, char **argv)
{
get_status(18671);

}

它不产生任何输出:

> ./a.out
Open Successful
>

procfs 的在线资料说我们可以简单地在 proc/<pid>/status 上做一只猫并检查进程的状态。

但在我的例子中它是一个二进制文件。我从未在任何地方看到它是二进制的。

有没有一种方法可以让我使用简单的 C 程序来获取当前进程的状态?

C++ 解决方案也是可以接受的。

最佳答案

这是你应该从/proc/pid/status 中读出的结构:

typedef struct pstatus {
int pr_flags; /* flags (see below) */
int pr_nlwp; /* number of active lwps in the process */
pid_t pr_pid; /* process id */
pid_t pr_ppid; /* parent process id */
pid_t pr_pgid; /* process group id */
pid_t pr_sid; /* session id */
id_t pr_aslwpid; /* historical; now always zero */
id_t pr_agentid; /* lwp id of the /proc agent lwp, if any */
sigset_t pr_sigpend; /* set of process pending signals */
uintptr_t pr_brkbase; /* address of the process heap */
size_t pr_brksize; /* size of the process heap, in bytes */
uintptr_t pr_stkbase; /* address of the process stack */
size_t pr_stksize; /* size of the process stack, in bytes */
timestruc_t pr_utime; /* process user cpu time */
timestruc_t pr_stime; /* process system cpu time */
timestruc_t pr_cutime; /* sum of children's user times */
timestruc_t pr_cstime; /* sum of children's system times */
sigset_t pr_sigtrace; /* set of traced signals */
fltset_t pr_flttrace; /* set of traced faults */
sysset_t pr_sysentry; /* set of system calls traced on entry */
sysset_t pr_sysexit; /* set of system calls traced on exit */
char pr_dmodel; /* data model of the process (see below) */
char pr_pad[3];
taskid_t pr_taskid; /* task id */
projid_t pr_projid; /* project id */
int pr_nzomb; /* number of zombie lwps in the process */
zoneid_t pr_zoneid; /* zone id */
int pr_filler[15]; /* reserved for future use */
lwpstatus_t pr_lwp; /* status of the representative lwp */
} pstatus_t;

请注意,它是在头文件 procfs.h 中定义的。声明一个 pstatus_t 变量并将 sizeof(pstatus_t) 字节读入该变量。

提示:同样不能通过ls获取,也可以使用/proc/self/psinfo读取自身进程的psinfo。

关于c++ - 使用 procf/<pid>/status 了解进程状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13469276/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com