Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

pcwiz

macrumors member
Original poster
May 28, 2008
55
0
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:

Code:
- (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
 
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).
 
The "@" is missing in the second argument. It should be @"ls /Volumes".
 
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:
Code:
[task setStandardInput:[NSPipe pipe]];
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.