objective-c – 无法访问NSTask启动路径.适用于Xcode. XCode显示错误

前端之家收集整理的这篇文章主要介绍了objective-c – 无法访问NSTask启动路径.适用于Xcode. XCode显示错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
好.关于堆栈溢出有几个问题. This question was the only question最接近地雷,但它使用通知.

代码非常简单.创建一个新的空Mac OSX项目,然后将以下代码粘贴到applicationDidFinishLaunching:方法中.它应该获取任何可执行文件的路径(在本例中为GIT).

@H_502_4@NSTask *aTask = [[NSTask alloc] init]; NSPipe *outputPipe = [NSPipe pipe]; NSPipe *errorPipe = [NSPipe pipe]; [aTask setStandardOutput: outputPipe]; [aTask setStandardError: errorPipe]; [aTask setArguments:[NSArray arrayWithObject:@"which"]]; [aTask setLaunchPath:@"/usr/bin/git"]; NSFileHandle *outputFileHandler = [outputPipe fileHandleForReading]; NSFileHandle *errorFileHandler = [errorPipe fileHandleForReading]; [aTask launch]; [aTask waitUntilExit]; // Task launched now just read and print the data NSData *data = [outputFileHandler readDataToEndOfFile]; NSString *outPutValue = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSData *errorData = [errorFileHandler readDataToEndOfFile]; NSString *errorValue = [[NSString alloc] initWithData:errorData encoding:NSUTF8StringEncoding]; NSLog(@"Error value: %@",errorValue); NSLog(@"Output Value: %@",outPutValue);

这段代码设置了两个读取管道并运行一个命令:git.

如果我在XCode中运行它,我会得到相应的结果:

@H_502_4@Error value: "" Output Value: /usr/bin/git

如果我转到我的build / Products / Debug文件夹并双击可执行文件,我会在控制台应用程序上打印此消息:

问:那么,这里的问题到底是什么?请不要做出替代解决方案……我也想知道问题是什么..谢谢.

解决方法

好的结果是答案是关于堆栈溢出,但它分散在不同的问题上.

这里问的问题是 – > Commands with NSTask和这里 – > NSTask launch path not accessible也是

但截至目前为止,他们的回答并不清楚问题所在.只有在阅读了NSTask not picking up $PATH from the user’s environment的问题之后(问题标题具有误导性),并且通过这两个答案NSTask not picking up $PATH from the user’s environmentFind out location of an executable file in Cocoa我才意识到解决方案.

It looks like this is about setting up either NS
Task or the user’s shell (e.g.,~/.bashrc) so that the correct
environment ($PATH) is seen by NSTask.

解:

@H_502_4@[task setLaunchPath:@"/bin/bash"]; NSArray *args = [NSArray arrayWithObjects:@"-l",@"-c",@"which git",//Assuming git is the launch path you want to run nil]; [task setArguments: args];

但是,这假设用户的shell始终是bash,而其他人则会失败.通过确定shell来解决这个问题.

@H_502_4@NSDictionary *environmentDict = [[NSProcessInfo processInfo] environment]; NSString *shellString = [environmentDict objectForKey:@"SHELL"];
原文链接:https://www.f2er.com/c/120200.html

猜你在找的C&C++相关文章