Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect which app is currently running on iOS using sysctl

Tags:

ios

sysctl

I have currently implemented a simple activity monitor to watch all running processes on iOS.

To retrieve a list of all running processes, I do this:

size_t size;
struct kinfo_proc *procs = NULL;
int status;
NSMutableArray *killedProcesses = [[NSMutableArray alloc] init];

int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };

status  = sysctl(mib, 4, NULL, &size, NULL, 0);
procs   = malloc(size);
status  = sysctl(mib, 4, procs, &size, NULL, 0);

// now, we have a nice list of processes

And if I want more information about a specific process, I'll do:

struct kinfo_proc *proc;
int mib[5] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pidNum, 0 };
int count;
size_t size = 0;

// ask the proc size
if(sysctl(mib, 4, NULL, &size, NULL, 0) < 0) return -1;

// allocate memory for proc
proc = (struct kinfo_proc *)malloc(size);

sysctl(mib, 4, proc, &size, NULL, 0);

All the extra proc info I want is now stored in proc.

I notice that apps won't be killed by the OS. Even when an app is not used for a long time (longer than 10 min.) it will remain in the process list. Even when I query what "state" the process has (proc->kp_proc.p_stat), it returns "running".

My question is: does anybody know a method to detect which PID is currently running/actively used (maybe: increasing cpu time? running time? cpu ticks etc.) ??

like image 804
hackerdiehack Avatar asked Sep 07 '12 14:09

hackerdiehack


1 Answers

Answering the "currently running" part of your question:

I used the code from this answer Can we retrieve the applications currently running in iPhone and iPad

Looked after the k_proc declarations here: http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/sys/proc.h

With trial and error found out that the processes with the p_flag set to 18432 is the currently running application (in this case this test).

See the first link, and replace the inner of the for cycle with:

if (process[i].kp_proc.p_flag == 18432){

                        NSString * processID    = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
                        NSString * processName  = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
                        NSString * status       = [[NSString alloc] initWithFormat:@"%d",process[i].kp_proc.p_flag ];

                        NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName,status, nil]
                                                                            forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessName",@"flag", nil]];

                        [array addObject:dict];

}
like image 64
Peteee24 Avatar answered Oct 13 '22 13:10

Peteee24