初衷:写了一个库,提供给其他人调用,在出错的时候写日记想把进程信息(主要是进程名,运行参数等)记录下来,忘了怎么做了(除了传入argv[0]和通过pipe调ps之外)。bs下自己,居然连pstat系列函数都忘了,还到CU去发帖问。
在HPUX上可以用pstat系列函数,可以查到大量的系统信息。在linux上可以查/proc下的文件。
这是HPUX上查进程名代码
void getprocinfo()
{
int r;
struct pst_status buf;
r = pstat_getproc(&buf,sizeof(buf),0,getpid());//指定getpid和elemcount=0查当前进程
if(r<0)
{
printf("get proc error %d/n",errno);
return ;
}
printf("/n/n------------------------------------------------------------------------------");
printf("/n %5s | %5s |%7s| %5s | %s", "PID", "UID", "Threads", "RSS", "Command");
printf("/n------------------------------------------------------------------------------");
printf("/n %5ld | ", buf.pst_pid);
printf("%5ld | ", buf.pst_uid);
printf("%5ld | ", buf.pst_nlwps);
printf("%5ld | ", buf.pst_rssize);
printf("%s/n ", buf.pst_cmd);
}
其中pst_status结构定义在/usr/include/sys/pm_pstat_body.h,有巨多的信息
列出所有进程:
void listproc()
{
struct pst_status * psa = NULL;
struct pst_status * prc = NULL;
struct pst_dynamic psd;
long nproc = 0;
long thsum = 0;
long i;
if ( pstat_getdynamic(&psd, sizeof(psd), 1, 0) == -1 )
(void)perror("pstat_getdynamic failed");
// Get the number of active processes from pst_dynamic
nproc = psd.psd_activeprocs;
psa = (struct pst_status *)malloc(nproc * sizeof(struct pst_status));
// Read the info about the active processes into the array 'psa'
if ( pstat_getproc(psa, sizeof(struct pst_status), nproc, 0) == -1 )
(void)perror("pstat_getproc failed");
(void)printf("/n/n------------------------------------------------------------------------------");
(void)printf("/n %5s | %5s | %10s |%7s| %5s | %5s| %5s|%s", "PID", "UID","UNAME", "Threads", "RSS", "Command");
(void)printf("/n------------------------------------------------------------------------------");
// Report the process info as required
prc = (struct pst_status *)psa;
int uid =getuid();
for (i=0; i < nproc; i++)
{
printf("/n %5ld | ", prc->pst_pid);
printf("%5ld | ", prc->pst_uid);
printf(" %10s |",getpwuid(prc->pst_uid)->pw_name);
printf("%5ld | ", prc->pst_nlwps);
printf("%5ld | ", prc->pst_rssize);
printf("%s ", prc->pst_cmd);
thsum += prc->pst_nlwps;
++prc;
}
(void)printf("/n/n*** %ld processes, %ld threads running/n/n", nproc, thsum);
(void)free(psa);
}