【问题标题】:How to get the active processes running in iOS如何让活动进程在 iOS 中运行
【发布时间】:2012-02-18 15:48:41
【问题描述】:

如何以编程方式获取在后台运行的活动进程、iOS 的 CPU 和 RAM 使用情况?

【问题讨论】:

标签: ios objective-c iphone system


【解决方案1】:

代码自解释:)

#import <mach/mach.h>
#import <mach/mach_host.h>
#import <sys/sysctl.h>
- (NSArray *)runningProcesses {

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

    size_t size;
    int st = sysctl(mib, miblen, NULL, &size, NULL, 0);

    struct kinfo_proc * process = NULL;
    struct kinfo_proc * newprocess = NULL;

    do {

        size += size / 10;
        newprocess = realloc(process, size);

        if (!newprocess){

            if (process){
                free(process);
            }

            return nil;
        }

        process = newprocess;
        st = sysctl(mib, miblen, process, &size, NULL, 0);

    } while (st == -1 && errno == ENOMEM);

    if (st == 0){

        if (size % sizeof(struct kinfo_proc) == 0){
            int nprocess = size / sizeof(struct kinfo_proc);

            if (nprocess){

                NSMutableArray * array = [[NSMutableArray alloc] init];

                for (int i = nprocess - 1; i >= 0; i--){

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

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

                free(process);
                return array;
            }
        }
    }

    return nil;
}

【讨论】:

  • sysctl 在 iOS9 中总是返回 0。
【解决方案2】:

在此处检索 CPU 使用率:iOS - Get CPU usage from application

RAM 使用似乎在这里解决:Available memory for iPhone OS app

编辑:

就像 EricS 在 cmets 中指出的那样,似乎有一种方法可以获取后台任务:Can we retrieve the applications currently running in iPhone and iPadHow to get information about free memory and running processes in an App Store approved app? (Yes, there is one!)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 2015-09-01
    • 2014-12-19
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多