Detect which app is currently running on iOS using sysctl

喜夏-厌秋 提交于 2019-11-27 01:02:58

问题


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.) ??


回答1:


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];

}


来源:https://stackoverflow.com/questions/12319817/detect-which-app-is-currently-running-on-ios-using-sysctl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!