I have code like following, it's ok, but I have 2 question about it.
1) If I assign some illegal para to sh, for example @"ls - l", then the outString is null. That is to say, it can not capture the error warning "ls: -: No such file or directory ls: l: No such file or directory". How can I deal with it?
2) How can I implement this function: given the app's current directory is "/user/Doc", and I perform sh = @"cd /", then I perform sh = @"ls -l" to see the content under the "/" directory at next loop. But when new loop starts, the current directory resume to "/user/Doc". How can I remain the task environment of last loop?
Furthermore, can I remain a persistent task to run "/bin/sh",just like work on the Terminal directly?
NSString *sh = @"ls -l";
while(sh != @"end"){
NSTask *shData = [[NSTask alloc] init];
[shData setLaunchPath: @"/bin/sh"];
NSArray *args;
args = [NSArray arrayWithObjects: @"-c", sh, nil];
[shData setArguments: args];
NSPipe *myPipe;
myPipe = [NSPipe pipe];
[shData setStandardOutput: myPipe];
[shData setStandardInput:[NSPipe pipe]];
NSFileHandle *file;
file = [myPipe fileHandleForReading];
[shData launch];
NSData *data1;
data1 = [file readDataToEndOfFile];
NSString *outString;
outString = [[NSString alloc] initWithData: data1 encoding: NSUTF8StringEncoding];
NSLog(@"%@",outString);
}
That string is on standard error, not standard output. Since you don't check the error stream, you won't find it.
That's not how subshells work. Google for "why is cd a shell builtin" for lots of information.