Search code examples
iospluginsprocesssandbox

iOS - get self process start time after the fact


I am writing a plugin bundle for iOS applications (I will spare you the details). When my bundle is loaded, which isn't necessarily when the main application bundle loads, I would like to get the "Uptime" of the process in seconds (or higher) resolution.

I know in other OS's (Unix / Linux / Android) I could enumerate the kinfo_procs or use the /proc/self/stat approach, but I wasn't able to achieve my goal from inside the iOS Application sandbox.

Is there some standard syscall / NSProcessInfo property I can use for that?

The purpose of this is mostly for debugging, but it could turn into a feature down the road. Therefore an approach that is eligible for AppStore is preferred, but not mandatory.


Solution

  • You can use [[NSProcessInfo processInfo] processIdentifier] to get the PID, and then sysctl to get the unix start time.

    I actually found another answer on SO for the same question, just on OSX: Is there any way to get the application's run time in Cocoa for OS X?

    #include <sys/sysctl.h>
    #include <sys/types.h>
    
    pid_t pid = [[NSProcessInfo processInfo] processIdentifier];
    int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
    struct kinfo_proc proc;
    size_t size = sizeof(proc);
    sysctl(mib, 4, &proc, &size, NULL, 0);
    
    NSDate *startTime = [NSDate dateWithTimeIntervalSince1970:proc.kp_proc.p_starttime.tv_sec];
    NSLog(@"Process start time for PID:%d is %@", pid, startTime);
    

    I'm not sure about App Store eligibility, but this worked for me both in the simulator and on device. Try submitting and let us know?