Advertisement
Guest User

Untitled

a guest
Oct 7th, 2015
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. //
  2. // main.m
  3. // process
  4. //
  5. // Created by piao on 15/8/13.
  6. // Copyright (c) 2015年 piao. All rights reserved.
  7. //
  8.  
  9. #import <Foundation/Foundation.h>
  10. #import <sys/sysctl.h>
  11. #import <signal.h>
  12. #import <unistd.h>
  13.  
  14.  
  15. NSArray *processInfo() {
  16.  
  17. int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
  18. size_t size;
  19. int st = sysctl(mib, sizeof(mib) / sizeof(CTL_KERN), NULL, &size, NULL, 0);
  20.  
  21. struct kinfo_proc * process = NULL;
  22. struct kinfo_proc * newprocess = NULL;
  23.  
  24. do {
  25. size += size / 10;
  26. newprocess = realloc(process, size);
  27.  
  28. if (!newprocess){
  29.  
  30. if (process){
  31. free(process);
  32. }
  33.  
  34. return nil;
  35. }
  36.  
  37. process = newprocess;
  38. st = sysctl(mib, sizeof(mib) / sizeof(CTL_KERN), process, &size, NULL, 0);
  39.  
  40. } while (st == -1 && errno == ENOMEM);
  41.  
  42. if (st == 0) {
  43.  
  44. if (size % sizeof(struct kinfo_proc) == 0){
  45. unsigned long nprocess = size / sizeof(struct kinfo_proc);
  46.  
  47. if (nprocess){
  48.  
  49. NSMutableArray * array = [[NSMutableArray alloc] init];
  50.  
  51. for (unsigned long i = 0; i < nprocess; i++){
  52.  
  53. NSNumber *processID = [NSNumber numberWithInt:process[i].kp_proc.p_pid];
  54. NSString *processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
  55.  
  56. NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
  57. forKeys:[NSArray arrayWithObjects:@"pid", @"name", nil]];
  58. [array addObject:dict];
  59. }
  60.  
  61. free(process);
  62. return array;
  63. }
  64. }
  65. }
  66.  
  67. return nil;
  68. }
  69.  
  70. int main(int argc, const char * argv[]) {
  71. @autoreleasepool {
  72. // insert code here...
  73. NSLog(@"process info:%@", processInfo());
  74. }
  75. return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement