NSProcessInfo: implement getting system uptime

Introduce the systemUptime property to NSProcessInfo, which can compute
platform-independently what is the uptime of the system.
This commit is contained in:
Daniel Ferreira 2017-06-21 09:59:31 +10:00 committed by Ivan Vučica
parent 277ae581a6
commit cbfa4d8cc9
3 changed files with 51 additions and 0 deletions

View file

@ -83,6 +83,14 @@ enum {
*/
+ (NSProcessInfo*) processInfo;
#if OS_API_VERSION(MAC_OS_X_VERSION_10_6,GS_API_LATEST)
#if GS_HAS_DECLARED_PROPERTIES
@property (readonly) NSUInteger systemUptime;
#else
- (NSUInteger) systemUptime;
#endif
#endif
/**
* Returns an array containing the arguments supplied to start this
* process.<br />

View file

@ -1465,6 +1465,43 @@ static void determineOperatingSystem()
return availMem;
}
- (NSUInteger) systemUptime
{
NSUInteger uptime = 0;
#if defined(_WIN32)
uptime = GetTickCount64() / 1000;
#elif defined(HAVE_SYSCTLBYNAME)
struct timeval tval;
size_t len = sizeof(tval);
if (sysctlbyname("kern.boottime", &tval, &len, 0, 0) == 0)
{
uptime = tval.tv_sec;
}
#elif defined(HAVE_PROCFS)
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath: @"/proc/uptime"])
{
NSString *uptimeContent = [NSString
stringWithContentsOfFile: @"/proc/uptime"];
NSString *uptimeString = [[uptimeContent
componentsSeparatedByString:@" "] objectAtIndex:0];
uptime = [uptimeString intValue];
}
#else
#warning "no known way to determine uptime on this system"
#endif
if (uptime == 0)
{
NSLog(@"Cannot determine uptime.");
}
return uptime;
}
@end
void

View file

@ -39,8 +39,14 @@ int main()
PASS((obj != nil && [obj isKindOfClass:[NSString class]] && [obj length] > 0),
"-operatingSystemName works");
NSLog(@"operatingSystemName %@", obj);
val = [info operatingSystem];
PASS(val != 0, "-operatingSystem works");
val = [info systemUptime];
NSLog(@"systemUptime %lu", val);
PASS(val != 0, "-systemUptime works");
obj = [info hostName];
PASS((obj != nil && [obj isKindOfClass:[NSString class]] && [obj length] > 0),
"-hostName works");