NSTask 没有从用户环境中获取 $PATH [英] NSTask not picking up $PATH from the user's environment
问题描述
我不知道为什么这个方法返回一个空字符串:
I don't know why this method returns a blank string:
- (NSString *)installedGitLocation {
NSString *launchPath = @"/usr/bin/which";
// Set up the task
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:launchPath];
NSArray *args = [NSArray arrayWithObject:@"git"];
[task setArguments:args];
// Set the output pipe.
NSPipe *outPipe = [[NSPipe alloc] init];
[task setStandardOutput:outPipe];
[task launch];
NSData *data = [[outPipe fileHandleForReading] readDataToEndOfFile];
NSString *path = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
return path;
}
如果不是传递 @"git"
作为参数,我传递 @"which"
我得到 /usr/bin/which
按预期返回.所以至少原理是有效的.
If instead of passing @"git"
as the argument, I pass @"which"
I get /usr/bin/which
returned as expected. So at least the principle works.
来自终端
$ which which
$ /usr/bin/which
$
$ which git
$ /usr/local/git/bin/git
所以它在那里工作.
我唯一能想到的是 which
没有搜索我环境中的所有路径.
The only thing I can think of is that which
isn't searching through all the paths in my environment.
这让我发疯!有人有什么想法吗?
This is driving me crazy! Does anyone have any ideas?
这看起来是关于设置 NSTask 或用户的 shell(例如,~/.bashrc),以便 NSTask 看到正确的环境($PATH).>
It looks like this is about setting up either NSTask or the user's shell (e.g., ~/.bashrc) so that the correct environment ($PATH) is seen by NSTask.
推荐答案
通过 NSTask 运行任务使用 fork()
和 exec()
来实际运行任务.根本不涉及用户的交互式 shell.由于 $PATH
(大体上)是一个 shell 概念,因此当您谈论以其他方式运行进程时,它并不适用.
Running a task via NSTask uses fork()
and exec()
to actually run the task. The user's interactive shell isn't involved at all. Since $PATH
is (by and large) a shell concept, it doesn't apply when you're talking about running processes in some other fashion.
这篇关于NSTask 没有从用户环境中获取 $PATH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!