ISIS Logo
UTILITIES
EPICS Utilities
getProcessUptime.cpp
Go to the documentation of this file.
1 #include <windows.h>
2 #include <tlhelp32.h>
3 
4 #include <string>
5 
6 #include <epicsMutex.h>
7 #include <epicsGuard.h>
8 
9 #include <epicsExport.h>
10 
11 #include "utilities.h"
12 
14 static double diffFileTimes(const FILETIME& f1, const FILETIME& f2)
15 {
16  ULARGE_INTEGER u1, u2;
17  u1.LowPart = f1.dwLowDateTime;
18  u1.HighPart = f1.dwHighDateTime;
19  u2.LowPart = f2.dwLowDateTime;
20  u2.HighPart = f2.dwHighDateTime;
21  return static_cast<double>(u1.QuadPart - u2.QuadPart) / 1e7;
22 }
23 
25 epicsShareFunc double getProcessUptime(const char* procExecutableName)
26 {
27  static epicsMutex procMutex;
28  HANDLE hProcess;
29  double procUptime = -1.0;
30  int procCount = 0; // number of procExecutableName processes found
31  PROCESSENTRY32 pe32;
32  FILETIME procCreationTime, procExitTime, procKernelTime, procUserTime, sysTime;
33  epicsGuard<epicsMutex> _lock(procMutex); // just to restrict number of simultaneous snapshots
34  HANDLE hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
35  if( hProcessSnap == INVALID_HANDLE_VALUE )
36  {
37  return procUptime;
38  }
39  pe32.dwSize = sizeof( PROCESSENTRY32 );
40  if( !Process32First( hProcessSnap, &pe32 ) )
41  {
42  CloseHandle( hProcessSnap );
43  return procUptime;
44  }
45  do
46  {
47  if ( !stricmp(pe32.szExeFile, procExecutableName) )
48  {
49  ++procCount;
50  hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe32.th32ProcessID);
51  if( hProcess != NULL )
52  {
53  if (GetProcessTimes(hProcess, &procCreationTime, &procExitTime, &procKernelTime, &procUserTime) != 0)
54  {
55  GetSystemTimeAsFileTime(&sysTime);
56  procUptime = diffFileTimes(sysTime, procCreationTime);
57  }
58  CloseHandle( hProcess );
59  }
60  }
61  } while( Process32Next( hProcessSnap, &pe32 ) );
62  CloseHandle( hProcessSnap );
63  return procUptime;
64 }
static double diffFileTimes(const FILETIME &f1, const FILETIME &f2)
filetime uses 100ns units, returns difference in seconds
epicsShareFunc double getProcessUptime(const char *procExecutableName)
returns -1.0 if process not running, else process uptime in seconds
Copyright © 2013 Science and Technology Facilities Council | Generated by   doxygen 1.8.5