开发者

Run terminal command with NSTask

开发者 https://www.devze.com 2023-03-25 13:55 出处:网络
I want to run a Terminal command in my program. The command looks like this: cd /path/to/file/; ./foo HTTPProxy 127.0.0.1

I want to run a Terminal command in my program. The command looks like this:

cd /path/to/file/; ./foo HTTPProxy 127.0.0.1

It works with system() but it doesn't work when I use NSTask.

system("cd /path/to/file/; ./foo HTTPProxy 127.0.0.1");

works fine but

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/path/to/file/./foo"];

NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHand开发者_Python百科leForReading];

[task setArguments:[NSArray arrayWithObjects:@"HTTPProxy 127.0.0.1", nil]];
[task launch];

NSData *data = [file readDataToEndOfFile];
NSString *string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(string);

doesn't. Output:

Command-line option 'HTTPProxy 127.0.0.1' with no value. Failing.

Has anybody an idea?


Now I think I have got it:

[task setArguments:[NSArray arrayWithObjects:@"HTTPProxy", @"127.0.0.1", nil]];

those are separate arguments in your invocation from the command line...

OLD ANSWER:

You could trying setting the current directory for execution:

– setCurrentDirectoryPath:

This is basically the effect of cd in the system version of your code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号