3

How can I get the directory path of other application from process pid?

Seems that there is no proc_pidpath calls on iOS.

timestee
  • 1,086
  • 12
  • 36

2 Answers2

3

The following works on iOS and uses sysctl which applications like Activity Monitor Touch are using in the App Store so should be acceptable to Apple. However, what you intend to do with the path once you've got it might not be acceptable to Apple. If you aren't intending to submit your app to the App Store then it is probably a non-issue.

- (NSString *)pathFromProcessID:(NSUInteger)pid {

    // First ask the system how big a buffer we should allocate
    int mib[3] = {CTL_KERN, KERN_ARGMAX, 0};

    size_t argmaxsize = sizeof(size_t);
    size_t size;

    int ret = sysctl(mib, 2, &size, &argmaxsize, NULL, 0);

    if (ret != 0) {
        NSLog(@"Error '%s' (%d) getting KERN_ARGMAX", strerror(errno), errno);            

        return nil;
    }

    // Then we can get the path information we actually want
    mib[1] = KERN_PROCARGS2;
    mib[2] = (int)pid;

    char *procargv = malloc(size);

    ret = sysctl(mib, 3, procargv, &size, NULL, 0);

    if (ret != 0) {
        NSLog(@"Error '%s' (%d) for pid %d", strerror(errno), errno, pid);            

        free(procargv);

        return nil;
    }

    // procargv is actually a data structure.  
    // The path is at procargv + sizeof(int)        
    NSString *path = [NSString stringWithCString:(procargv + sizeof(int))
                                        encoding:NSASCIIStringEncoding];

    free(procargv);

    return(path);
}
mttrb
  • 8,297
  • 3
  • 35
  • 57
  • Not working so well both on osx and iOS, only several applications seems right,many applications path is unreadable like: -x|~o#@0f – timestee Apr 15 '12 at 08:52
  • Hmmm, let me have another look. – mttrb Apr 15 '12 at 08:55
  • I've added some error checking to the calls to sysctl. When I run the above on my iPhone (non-jailbroken iOS 5.1) I don't see any garbage paths but I do get a number of sysctl errors trying to access the information for some system process. At the moment I am assuming this is a permissions issue. I have modified the method to return nil in these cases. – mttrb Apr 15 '12 at 09:27
  • Is `sysctl()` working corretly on 64-bit processors too? because on iPhone 5S it returns a very big size for me, and I get an error. `malloc: *** mach_vm_map(size=4295229440) failed (error code=3) *** error: can't allocate region` – dragos2 May 14 '14 at 14:11
0

Things on iOS are a bit more restricted than that. If you wish to share files between applications, consider using the iCloud - it will allow you to access files across different platforms and even different apps, given that the developer id that the apps belong to is the same. Ray Wenderlich wrote a helpful tutorial about this. Good luck!

Stavash
  • 14,244
  • 5
  • 52
  • 80