使用 NSTask 运行终端命令
我想在我的程序中运行终端命令。 该命令如下所示:
cd /path/to/file/; ./foo HTTPProxy 127.0.0.1
它适用于 system()
,但当我使用 NSTask
时它不起作用。
system("cd /path/to/file/; ./foo HTTPProxy 127.0.0.1");
工作正常但
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/path/to/file/./foo"];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[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);
没有。 输出:
Command-line option 'HTTPProxy 127.0.0.1' with no value. Failing.
有人有想法吗?
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 fileHandleForReading];
[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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
现在我想我已经明白了:
这些是从命令行调用中的单独参数...
旧答案:
您可以尝试设置当前执行目录:
这基本上是 cd 的效果代码的
系统
版本。Now I think I have got it:
those are separate arguments in your invocation from the command line...
OLD ANSWER:
You could trying setting the current directory for execution:
This is basically the effect of
cd
in thesystem
version of your code.