1
votes

I'm trying to learn writing a NSTask in such a way that the task process can accept input file redirection as argument. In traditional unix system() command this is trivial to code, but too far from being controllable enough for the demands of my app. The example of what I'm trying to understand is which argument belongs where. This is the full command, as would be typed into stdin or passed to system():

cd /Users/Shared ; /usr/local/bin/C_command < /Users/Shared/s.txt

where C_command stands for a standard unix command-line tool which accepts input arguments redirected to be read from a file, exactly as written. Launch path would then be:

task.launchPath = @"/usr/local/bin/C_command";

Current directory would have to be:

task.currentDirectoryPath = @"/Users/Shared";

If putting the following as argument:

NSArray *args = [NSArray arrayWithObjects:[NSString stringWithFormat: @" < /Users/shared/s.txt"], nil];

or even this:

NSArray *args = [NSArray arrayWithObjects:[NSString stringWithFormat: @" < "], [NSString stringWithFormat: @"/Users/shared/s.txt"], nil];

I'm obviously doing something wrong and missing something evidently important, but can't figure out what. A hint is very welcome. Thanks!

1

1 Answers

2
votes

Input redirection just uses the contents of a file instead of the contents of stdin. You have to hook up the NSTask object's stdin to the file. Something like this should work:

NSTask *task = [[NSTask alloc] init];
NSFileHandle *stdin = [NSFileHandle fileHandleForReadingAtPath:@"/Users/shared/s.txt"];
[task setLaunchPath:@"/usr/local/bin/C_command"];
[task setCurrentDirectoryPath:@"/Users/Shared"];
[task setStandardInput:stdin];