PDA

View Full Version : NSTask "/bin/sh -c" trick doesnt work




pcwiz
Aug 4, 2009, 08:48 PM
Hi,

I've heard of a method to use NSTask by specifying /bin/sh as the launch path, "-c" as the first argument, your command as the second argument and nil as the third argument. I have this code that tries to do a simple "ls /Volumes" command:

- (IBAction)runTask:(id)sender {
NSLog(@"starting");
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-c", "ls /Volumes", nil];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"got\n%@", string);
}

But it either a) doesnt return an output or b) crashes the app (cant remember which as im not at my computer right now. Any help would be appreciated.

Thanks



Cinder6
Aug 4, 2009, 09:53 PM
From what I remember of how execvp() works in C, you might need to separate "ls /Volumes" into two different array elements: ("-c", "ls", "/Volumes", nil). That's how I have it in my old shell replacement program I had to write for school a few semesters ago. NSTask might work the same way (I've never had occasion to use it).

ncl
Aug 5, 2009, 05:54 AM
The "@" is missing in the second argument. It should be @"ls /Volumes".

Cinder6
Aug 5, 2009, 01:38 PM
The "@" is missing in the second argument. It should be @"ls /Volumes".

Good eye.

pcwiz
Aug 8, 2009, 06:15 PM
I fixed that @ and the app is no longer crashing, however it still does not return an output.

I even tried using this example directly and it did not work:

http://borkware.com/quickies/single?id=130

Was the /bin/sh -c trick disabled in Leopard or something?

ncl
Aug 9, 2009, 04:00 AM
The problem is explained here (at the bottom of the page):
http://www.cocoadev.com/index.pl?NSTask
Apparently, NSLog, printf, etc. stop working after starting a shell with NSTask. Note that the problem is only with Xcode's console. If you look at the output of your application with Console.app, you should see the result of the task.
The fix is to add:

[task setStandardInput:[NSPipe pipe]];

pcwiz
Aug 10, 2009, 12:59 PM
Thanks, that helps a lot :)