NSTask "/bin/sh -c" trick doesnt work

Discussion in 'Mac Programming' started by pcwiz, Aug 4, 2009.

  1. pcwiz macrumors member

    Joined:
    May 28, 2008
    #1
    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
     
  2. Cinder6 macrumors 6502

    Cinder6

    Joined:
    Jul 9, 2009
    #2
    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).
     
  3. ncl macrumors member

    Joined:
    Aug 16, 2008
    #3
    The "@" is missing in the second argument. It should be @"ls /Volumes".
     
  4. Cinder6 macrumors 6502

    Cinder6

    Joined:
    Jul 9, 2009
    #4
    Good eye.
     
  5. pcwiz thread starter macrumors member

    Joined:
    May 28, 2008
    #5
    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?
     
  6. ncl macrumors member

    Joined:
    Aug 16, 2008
    #6
    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]];
    
     
  7. pcwiz thread starter macrumors member

    Joined:
    May 28, 2008

Share This Page