Abs
Abs

Reputation: 57966

Get Process ID for a launched application using NSWorkspace

I am having difficulty getting the pid of a launched file in an application. I think I'm nearly there but I keep getting a null:

[sharedWorkspace openFile:@"/Users/abs/Documents/my.txt" withApplication:@"TextEdit"]; 

 NSDictionary * currentAppInfo = [sharedWorkspace activeApplication];

 int pid = [[currentAppInfo objectForKey: @"NSApplicationProcessIdentifier"] intValue];

 NSLog(@"%@", pid); // (null), using @i, @u, @d I get 0

What am I doing wrong here?

This is for a commnand line application being built in xcode 4.2.

Upvotes: 2

Views: 4543

Answers (2)

Jef
Jef

Reputation: 2134

Assuming you have included the Cocoa/AppKit framework; You can get the process ID of an app by filtering NSWorkspace's runningApplications for TextEdit and then get its processIdentifier property.

NSLog(@"%i", [[NSRunningApplication runningApplicationsWithBundleIdentifier: @"com.apple.TextEdit"] processIdentifier]);

(I'm not behind my Mac right now so this is untested)

Upvotes: 1

Michael Dautermann
Michael Dautermann

Reputation: 89559

If you're doing your app as a command line application, you are likely not even using AppKit. Is the AppKit.framework linked in your project?

Does the [NSWorkspace openFile: withApplication:] call even work?

Check out this CocoaBuilder thread. One quote that stands out to me is:

AppKit in general requires a window server connection.

To get the process id (pid) of the TextEdit you launched, I believe you're going to have to try something else.

Of course you realize that [NSWorkspace activeApplication] has been deprecated as of 10.7, yes?

Upvotes: 2

Related Questions