Getting the pid of the process

Hi, ALL,


When I tried to execute the following code:


[code]

NSWorkspace *ws = [NSWorkspace sharedWorkspace];
NSRunningApplication *app = [ws launchApplicationAtURL:url options:NSWorkspaceLaunchAsync
configuration:[NSDictionary dictionaryWithObject:params forKey:NSWorkspaceLaunchConfigurationArguments]
error:&error];
[params release];

if( app != nil )
pid = [app processIdentifier];

[/code]


and supply "/bin/ls" I'm getting "-1" as a pid.


However when I tried to run the app bundle, I'm getting the appropriate pid of the bundle.


Is there a solution for "one fits all"? Or I will have to rely om the fact that the pid of non-bundle application will always be "-1"?


Thank you.

Replies

Well, first, "ls" is not an application. It's an executable, sure, but not all executables are applications. It's not appropriate to try to launch it using NSWorkspace, nor would NSRunningApplication properly represent it (because it's not a running application).


You should use NSTask to run commands like "ls". (Well, for "ls" specifically, you should use the appropriate directory enumeration APIs and not invoke an external command at all.)


What are you intending to use the process identifier for? Perhaps there's a more appropriate way to achieve what you're trying to do.


For what it's worth, the docs for -[NSRunningApplication processIdentifier] says it may return -1, but doesn't really explain why. My best guess is for NSRunningApplication objects that represent terminated apps/processes, which don't exist anymore.

Hi, Ken,

I tried to rewrite an old Carbon code which checked if there is an executable with the .app extension and if not just grabbed the pid of that process. But in case it was an .app executabe (i.e. app bunde) it didn't get the pid.


So I wrote the code above - which apparently broke the case with "ls", because it just wrongly presumed that it will work in any case.


So I can try to add the follwing code:


[code]

NSURL *url = [NSURL fileURLWithPath:myPath isDirectory:YES];
NSBundle *bundle = [NSBundle bundleWithURL:url];
if( bundle == nil )
{
printf( "Not a bundle!!";
return -1;
}
[/code]


before the one above, but I was told that launchApplicationAtURL perform a sanity check.


So, is there a "one-solution-fits-all"?


Thank you.

But what is the code going to do with the pid? Why is it trying to obtain the pid?