views:

266

answers:

1

Here is my code:

task = [[NSTask alloc] init];
[task setCurrentDirectoryPath:@"/applications/jarvis/brain/"];
[task setLaunchPath:@"/applications/jarvis/brain/server.sh"];

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

[task launch];
[task waitUntilExit];
[task release];

NSFileHandle * read = [out fileHandleForReading];
NSData * dataRead = [read readDataToEndOfFile];
NSString * stringRead = [[[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding] autorelease];

So I'm trying to replicate this:

cd /applications/jarvis/brain/
./server.sh

but using NSTask in objective-c.

For some reason though, when I run this code, stringRead, returns nothing. It should return what terminal is returning when I launch the .sh file. Correct?

Any ideas?

Elijah

+3  A: 

Xcode Bug
There's a bug in Xcode that stops it from printing any output after a a new task using standard output is launched (it collects all output, but no longer prints anything). You're going to have to call [task setStandardInput:[NSPipe pipe]] to get it to show output again (or, alternatively, have the task print to stderr instead of stdout).


Suggestion for final code:

NSTask *server = [NSTask new];
[server setLaunchPath:@"/bin/sh"];
[server setArguments:[NSArray arrayWithObject:@"/path/to/server.sh"]];
[server setCurrentDirectoryPath:@"/path/to/current/directory/"];

NSPipe *outputPipe = [NSPipe pipe];
[server setStandardInput:[NSPipe pipe]];
[server setStandardOutput:outputPipe];

[server launch];
[server waitUntilExit]; // Alternatively, make it asynchronous.
[server release];

NSData *outputData = [[outputPipe fileHandleForReading] readDataToEndOfFile];
NSString *outputString = [[[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding] autorelease]; // Autorelease optional, depending on usage.
itaiferber
It seems like this is freezing my code as well...huh...any other ideas?
Elijah W.
And, I tried to put in echo "hello world" it returned blank....and date retured blank.
Elijah W.
Even with `[server setStandardInput:[NSPipe pipe]]`? That's a little bit strange. Did you copy my code verbatim? Try it, and see if it'll work with a file that just contains `echo "Hello World"; pwd | ls`.If it still doesn't work, please tell us what version of Xcode you're using, and see if writing the string to file produces any output (it might just be the Xcode terminal not printing any more output).
itaiferber
GOT IT!!! User error...Thanks for your help!
Elijah W.
Great, glad it works... :)
itaiferber