⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hr_swrun.c

📁 Snmp(简单网管协议)软件包。
💻 C
📖 第 1 页 / 共 2 页
字号:
/* *  Host Resources MIB - Running Software group implementation - hr_swrun.c *	(also includes Running Software Performance group ) * */#include <config.h>#if HAVE_STDLIB_H#include <stdlib.h>#endif#include <fcntl.h>#if HAVE_UNISTD_H#include <unistd.h>#endif#include <sys/param.h>#include <ctype.h>#if HAVE_SYS_PSTAT_H#include <sys/pstat.h>#endif#if HAVE_SYS_USER_H#ifdef solaris2#define _KMEMUSER#endif#include <sys/user.h>#endif#if HAVE_SYS_PROC_H#include <sys/proc.h>#endif#if HAVE_KVM_H#include <kvm.h>#endif#if HAVE_SYS_SYSCTL_H#include <sys/sysctl.h>#endif#if HAVE_DIRENT_H && !defined(cygwin)#include <dirent.h>#else# define dirent direct# if HAVE_SYS_NDIR_H#  include <sys/ndir.h># endif# if HAVE_SYS_DIR_H#  include <sys/dir.h># endif# if HAVE_NDIR_H#  include <ndir.h># endif#endif#ifdef cygwin#include <windows.h>#include <sys/cygwin.h>#include <tlhelp32.h>#include <psapi.h>#endif#if _SLASH_PROC_METHOD_#include <procfs.h>#endif#if HAVE_STRING_H#include <string.h>#else#include <strings.h>#endif#include <stdio.h>#include "snmp_logging.h"#include "host_res.h"#include "hr_swrun.h"#include "auto_nlist.h"#include "kernel.h"#if solaris2#include "kernel_sunos5.h"#endif	/*********************	 *	 *  Initialisation & common implementation functions	 *	 *********************/void  Init_HR_SWRun (void);int   Get_Next_HR_SWRun (void);void  End_HR_SWRun (void);int header_hrswrun (struct variable *,oid *, size_t *, int, size_t *, WriteMethod **);int header_hrswrunEntry (struct variable *,oid *, size_t *, int, size_t *, WriteMethod **);#ifdef cygwinstatic struct external_pinfo *curproc;static struct external_pinfo lowproc;#elif !defined(linux)static int LowProcIndex;#endif#ifdef hpux10struct pst_status *proc_table;struct pst_dynamic pst_dyn;#elif HAVE_KVM_GETPROCSstruct kinfo_proc *proc_table;#elif defined(solaris2)int *proc_table;#elsestruct proc *proc_table;#endifint current_proc_entry;#define	HRSWRUN_OSINDEX		1#define	HRSWRUN_INDEX		2#define	HRSWRUN_NAME		3#define	HRSWRUN_ID		4#define	HRSWRUN_PATH		5#define	HRSWRUN_PARAMS		6#define	HRSWRUN_TYPE		7#define	HRSWRUN_STATUS		8#define	HRSWRUNPERF_CPU		9#define	HRSWRUNPERF_MEM		10struct variable4 hrswrun_variables[] = {    { HRSWRUN_OSINDEX,   ASN_INTEGER, RONLY, var_hrswrun, 1, {1}},    { HRSWRUN_INDEX,     ASN_INTEGER, RONLY, var_hrswrun, 3, {2,1,1}},    { HRSWRUN_NAME,    ASN_OCTET_STR, RONLY, var_hrswrun, 3, {2,1,2}},    { HRSWRUN_ID,      ASN_OBJECT_ID, RONLY, var_hrswrun, 3, {2,1,3}},    { HRSWRUN_PATH,    ASN_OCTET_STR, RONLY, var_hrswrun, 3, {2,1,4}},    { HRSWRUN_PARAMS,  ASN_OCTET_STR, RONLY, var_hrswrun, 3, {2,1,5}},    { HRSWRUN_TYPE,      ASN_INTEGER, RONLY, var_hrswrun, 3, {2,1,6}},    { HRSWRUN_STATUS,    ASN_INTEGER, RONLY, var_hrswrun, 3, {2,1,7}}};struct variable4 hrswrunperf_variables[] = {    { HRSWRUNPERF_CPU,   ASN_INTEGER, RONLY, var_hrswrun, 3, {1,1,1}},    { HRSWRUNPERF_MEM,   ASN_INTEGER, RONLY, var_hrswrun, 3, {1,1,2}}};oid hrswrun_variables_oid[]     = { 1,3,6,1,2,1,25,4 };oid hrswrunperf_variables_oid[] = { 1,3,6,1,2,1,25,5 };#ifdef cygwin/* * a lot of this is "stolen" from cygwin ps.cc */typedef BOOL (WINAPI *ENUMPROCESSMODULES) (    HANDLE hProcess,    HMODULE *lphModule,    DWORD cb,    LPDWORD lpcbNeeded);typedef DWORD (WINAPI *GETMODULEFILENAME) (    HANDLE hProcess,    HMODULE hModule,    LPTSTR lpstrFIleName,    DWORD nSize);typedef DWORD (WINAPI *GETPROCESSMEMORYINFO) (    HANDLE hProcess,    PPROCESS_MEMORY_COUNTERS pmc,    DWORD nSize);typedef HANDLE (WINAPI *CREATESNAPSHOT) (    DWORD dwFlags,    DWORD th32ProcessID);typedef BOOL (WINAPI *PROCESSWALK) (    HANDLE hSnapshot,    LPPROCESSENTRY32 lppe);ENUMPROCESSMODULES myEnumProcessModules;GETMODULEFILENAME myGetModuleFileNameEx;CREATESNAPSHOT myCreateToolhelp32Snapshot;PROCESSWALK myProcess32First;PROCESSWALK myProcess32Next;GETPROCESSMEMORYINFO myGetProcessMemoryInfo = NULL;cygwin_getinfo_types query = CW_GETPINFO;static BOOL WINAPI dummyprocessmodules(    HANDLE hProcess,    HMODULE *lphModule,    DWORD cb,    LPDWORD lpcbNeeded){    lphModule[0] = (HMODULE) *lpcbNeeded;    *lpcbNeeded = 1;    return 1;}static DWORD WINAPI GetModuleFileNameEx95(    HANDLE hProcess,    HMODULE hModule,    LPTSTR lpstrFileName,    DWORD n){    HANDLE h;    DWORD pid = (DWORD) hModule;    PROCESSENTRY32 proc;    h = myCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);    if (!h) return 0;    proc.dwSize = sizeof(proc);    if (myProcess32First(h, &proc))      do        if (proc.th32ProcessID == pid) {	    CloseHandle(h);	    strcpy(lpstrFileName, proc.szExeFile);	    return 1;	}      while (myProcess32Next(h, &proc));    CloseHandle(h);    return 0;}#define FACTOR (0x19db1ded53ea710LL)#define NSPERSEC 10000000LL#define NSPERMSEC 10000LLstatic time_t __stdcallto_time_t(PFILETIME ptr){    long rem;    long long x = ((long long)ptr->dwHighDateTime << 32) + ((unsigned)ptr->dwLowDateTime);    x -= FACTOR;    rem = x % NSPERSEC;    rem += NSPERSEC/2;    x /= NSPERSEC;    x += rem/NSPERSEC;    return x;}static long to_msec(PFILETIME ptr){    long long x = ((long long)ptr->dwHighDateTime << 32) + (unsigned)ptr->dwLowDateTime;    x /= NSPERMSEC;    return x;}#endif /* cygwin */void init_hr_swrun(void){#ifdef cygwin    OSVERSIONINFO ver;    HMODULE h;    memset(&ver, 0, sizeof ver);    ver.dwOSVersionInfoSize = sizeof ver;    GetVersionEx(&ver);    if (ver.dwPlatformId == VER_PLATFORM_WIN32_NT) {	h = LoadLibrary("psapi.dll");	if (h) {	    myEnumProcessModules = (ENUMPROCESSMODULES) GetProcAddress(h, "EnumProcessModules");	    myGetModuleFileNameEx = (GETMODULEFILENAME) GetProcAddress(h, "GetModuleFileNameExA");	    myGetProcessMemoryInfo = (GETPROCESSMEMORYINFO) GetProcAddress(h, "GetProcessMemoryInfo");	    if (myEnumProcessModules && myGetModuleFileNameEx)		query = CW_GETPINFO_FULL;	    else		snmp_log(LOG_ERR, "hr_swrun failed NT init\n");	}	else	    snmp_log(LOG_ERR, "hr_swrun failed to load psapi.dll\n");    }    else {	h = GetModuleHandle("KERNEL32.DLL");	myCreateToolhelp32Snapshot = (CREATESNAPSHOT) GetProcAddress(h, "CreateToolhelp32Snapshot");	myProcess32First = (PROCESSWALK) GetProcAddress(h, "Process32First");	myProcess32Next = (PROCESSWALK) GetProcAddress(h, "Process32Next");	myEnumProcessModules = dummyprocessmodules;	myGetModuleFileNameEx = GetModuleFileNameEx95;	if (myCreateToolhelp32Snapshot && myProcess32First && myProcess32Next)#if 0	    /* This doesn't work after all on Win98 SE */	    query = CW_GETPINFO_FULL;#else	    query = CW_GETPINFO;#endif	else	    snmp_log(LOG_ERR, "hr_swrun failed non-NT init\n");    }#endif /* cygwin */#ifdef PROC_SYMBOL    auto_nlist( PROC_SYMBOL,0,0 );#endif#ifdef NPROC_SYMBOL    auto_nlist( NPROC_SYMBOL,0,0 );#endif    proc_table = 0;    REGISTER_MIB("host/hr_swrun", hrswrun_variables, variable4, hrswrun_variables_oid);    REGISTER_MIB("host/hr_swrun", hrswrunperf_variables, variable4, hrswrunperf_variables_oid);}/*  header_hrswrun(...  Arguments:  vp	  IN      - pointer to variable entry that points here  name    IN/OUT  - IN/name requested, OUT/name found  length  IN/OUT  - length of IN/OUT oid's   exact   IN      - TRUE if an exact match was requested  var_len OUT     - length of variable or 0 if function returned  write_method  */intheader_hrswrun(struct variable *vp,	       oid *name,	       size_t *length,	       int exact,	       size_t *var_len,	       WriteMethod **write_method){#define HRSWRUN_NAME_LENGTH	9    oid newname[MAX_OID_LEN];    int result;    DEBUGMSGTL(("host/hr_swrun", "var_hrswrun: "));    DEBUGMSGOID(("host/hr_swrun", name, *length));    DEBUGMSG(("host/hr_swrun"," %d\n", exact));    memcpy( (char *)newname,(char *)vp->name, vp->namelen * sizeof(oid));    newname[HRSWRUN_NAME_LENGTH] = 0;    result = snmp_oid_compare(name, *length, newname, vp->namelen + 1);    if ((exact && (result != 0)) || (!exact && (result >= 0)))        return(MATCH_FAILED);    memcpy( (char *)name,(char *)newname, (vp->namelen + 1) * sizeof(oid));    *length = vp->namelen + 1;    *write_method = 0;    *var_len = sizeof(long);	/* default to 'long' results */    return(MATCH_SUCCEEDED);}intheader_hrswrunEntry(struct variable *vp,		    oid *name,		    size_t *length,		    int exact,		    size_t *var_len,		    WriteMethod **write_method){#define HRSWRUN_ENTRY_NAME_LENGTH	11    oid newname[MAX_OID_LEN];    int pid, LowPid=-1;    int result;    DEBUGMSGTL(("host/hr_swrun", "var_hrswrunEntry: "));    DEBUGMSGOID(("host/hr_swrun", name, *length));    DEBUGMSG(("host/hr_swrun"," %d\n", exact));    memcpy( (char *)newname,(char *)vp->name, vp->namelen * sizeof(oid));		/*	 	 *  Find the "next" running process		 */    Init_HR_SWRun();    for ( ;; ) {        pid = Get_Next_HR_SWRun();#ifndef linux        DEBUGMSG(("host/hr_swrun",                  "(index %d (entry #%d) ....", pid, current_proc_entry));#endif        if ( pid == -1 )	    break;	newname[HRSWRUN_ENTRY_NAME_LENGTH] = pid;	DEBUGMSGOID(("host/hr_swrun", newname, *length));	DEBUGMSG(("host/hr_swrun","\n"));        result = snmp_oid_compare(name, *length, newname, vp->namelen + 1);        if (exact && (result == 0)) {	    LowPid = pid;#ifdef cygwin	    lowproc = *curproc;#elif !defined(linux)	    LowProcIndex = current_proc_entry-1;#endif	    DEBUGMSGTL(("host/hr_swrun", " saved\n"));	    /* Save process status information */            break;	}	if ((!exact && (result < 0)) &&		( LowPid == -1 || pid < LowPid )) {	    LowPid = pid;#ifdef cygwin	    lowproc = *curproc;#elif !defined(linux)	    LowProcIndex = current_proc_entry-1;#endif	    /* Save process status information */	    DEBUGMSG(("host/hr_swrun", " saved"));	}	DEBUGMSG(("host/hr_swrun", "\n"));    }    End_HR_SWRun();    if ( LowPid == -1 ) {        DEBUGMSGTL(("host/hr_swrun", "... index out of range\n"));        return(MATCH_FAILED);    }    newname[HRSWRUN_ENTRY_NAME_LENGTH] = LowPid;    memcpy( (char *)name,(char *)newname, (vp->namelen + 1) * sizeof(oid));    *length = vp->namelen + 1;    *write_method = 0;    *var_len = sizeof(long);	/* default to 'long' results */    DEBUGMSGTL(("host/hr_swrun", "... get process stats "));    DEBUGMSGOID(("host/hr_swrun", name, *length));    DEBUGMSG(("host/hr_swrun","\n"));    return LowPid;}	/*********************	 *	 *  System specific implementation functions	 *	 *********************/u_char *var_hrswrun(struct variable *vp,	    oid *name,	    size_t *length,	    int exact,	    size_t *var_len,	    WriteMethod **write_method){    int pid=0;    static char string[256];#ifdef HAVE_SYS_PSTAT_H    struct pst_status proc_buf;#elif defined(solaris2)#if _SLASH_PROC_METHOD_    static psinfo_t psinfo;    static psinfo_t *proc_buf;    int procfd;    char procfn[sizeof "/proc/00000/psinfo"];#else    static struct proc *proc_buf;    char *cp1;#endif	/* _SLASH_PROC_METHOD_ */    static time_t when = 0;    time_t now;    static int oldpid = -1;#endif#if HAVE_KVM_GETPROCS    char **argv;#endif#ifdef linux    FILE *fp;    char buf[256];    int i;#endif    char *cp;    if ( vp->magic == HRSWRUN_OSINDEX ) {        if (header_hrswrun(vp, name, length, exact, var_len, write_method) == MATCH_FAILED )	    return NULL;    }    else {                pid = header_hrswrunEntry(vp, name, length, exact, var_len, write_method);        if ( pid == MATCH_FAILED )	    return NULL;    }#ifdef HAVE_SYS_PSTAT_H    if (pstat_getproc( &proc_buf, sizeof(struct pst_status), 0, pid ) == -1)	return NULL;#elif defined(solaris2)    time(&now);    if (pid == oldpid) {	if (now != when) oldpid = -1;    }    if (oldpid != pid || proc_buf == NULL) {#if _SLASH_PROC_METHOD_	proc_buf = &psinfo;	sprintf(procfn, "/proc/%.5d/psinfo", pid);	if ((procfd = open(procfn, O_RDONLY)) != -1) {		if (read(procfd, proc_buf, sizeof(*proc_buf)) != sizeof(*proc_buf)) abort();		close(procfd);	} else		proc_buf = NULL;#else	if (kd == NULL) return NULL;	if ((proc_buf = kvm_getproc(kd, pid)) == NULL) return NULL;#endif	oldpid = pid;	when = now;    }#endif    switch (vp->magic){	case HRSWRUN_OSINDEX:#if NO_DUMMY_VALUES		return NULL;#else	    long_return = 1;		/* Probably! */	    return (u_char *)&long_return;#endif	case HRSWRUN_INDEX:	    long_return = pid;	    return (u_char *)&long_return;	case HRSWRUN_NAME:#ifdef HAVE_SYS_PSTAT_H	    sprintf(string, "%s", proc_buf.pst_cmd);	    cp = strchr( string, ' ');	    if ( cp != NULL )		*cp = '\0';#elif defined(solaris2)#if _SLASH_PROC_METHOD_	    if (proc_buf)		    strcpy(string, proc_buf->pr_fname);	    else		    strcpy(string, "<exited>");#else	    strcpy(string, proc_buf->p_user.u_comm);#endif#elif HAVE_KVM_GETPROCS            strcpy(string, proc_table[LowProcIndex].kp_proc.p_comm);#elif defined(linux)	    sprintf( string, "/proc/%d/status", pid );	    if ((fp = fopen( string, "r")) == NULL) return NULL;	    fgets( buf, sizeof(buf), fp );	/* Name: process name */	    cp = buf;	    while ( *cp != ':' )		++cp;	    ++cp;	    while ( isspace( *cp ))		++cp;	    strcpy( string, cp );            fclose(fp);#elif defined(cygwin)	    if (lowproc.process_state & (PID_ZOMBIE | PID_EXITED))		strcpy(string, "<defunct>");	    else if (lowproc.ppid) {		cygwin_conv_to_posix_path(lowproc.progname, string);		cp = strrchr(string, '/');		if (cp) strcpy(string, cp+1);	    }	    else if (query == CW_GETPINFO_FULL) {		DWORD n = lowproc.dwProcessId & 0xffff;		HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,				       FALSE, n);		if (h) {		    HMODULE hm[1000];		    if (!myEnumProcessModules(h, hm, sizeof hm, &n)) {			snmp_log(LOG_DEBUG, "no module handle for %lu\n", n);			n = 0;		    }		    if (n && myGetModuleFileNameEx(h, hm[0], string, sizeof string)) {			cp = strrchr(string, '\\');			if (cp) strcpy(string, cp+1);		    }		    else			strcpy(string, "*** unknown");		    CloseHandle(h);		}		else {		    snmp_log(LOG_INFO, "no process handle for %lu\n", n);		    strcpy(string, "** unknown");		}	    }	    else		strcpy(string, "* unknown");	    cp = strchr(string, '\0') - 4;	    if (cp > string && strcasecmp(cp, ".exe") == 0)		*cp = '\0';#else#if NO_DUMMY_VALUES	    return NULL;#endif	    sprintf(string, "process name");#endif	    *var_len = strlen(string);	    /* remove trailing newline */	    if (*var_len) {	        cp = string + *var_len -1;	        if (*cp == '\n')	            --(*var_len);	    }	    return (u_char *) string;	case HRSWRUN_ID:            *var_len = nullOidLen;	    return (u_char *) nullOid;	case HRSWRUN_PATH:#ifdef HAVE_SYS_PSTAT_H		/* Path not available - use argv[0] */	    sprintf(string, "%s", proc_buf.pst_cmd);	    cp = strchr( string, ' ');	    if ( cp != NULL )		*cp = '\0';#elif defined(solaris2)#ifdef _SLASH_PROC_METHOD_

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -