NSTask launch 或 popen 在 macOS 中启动简单的 Bash 脚本需要 15-20 秒

问题描述

我有简单的代码可以基于简单的 popen 和读取缓冲区从 C++ 在 macOS 中启动外部进程。启动我的外部脚本大约需要 15-20 秒。

     char buffer[128];
     std::string result = "";
     FILE* pipe = popen(cmd,"r");
     if (!pipe) throw std::runtime_error("popen() failed!");
     try {
         while (fgets(buffer,sizeof buffer,pipe) != NULL) {
             result += buffer;
         }
     } catch (...) {
         pclose(pipe);
         throw;
     }
     pclose(pipe);
     return result;
 }

然后我尝试了基于 [NSTask launch] 的其他方法:

    NSString *commandToRun = FUN_ConvertCStringToNSString(cmd);
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/sh"];

    NSArray *arguments = [NSArray arrayWithObjects:
                          @"-c",[NSString stringWithFormat:@"%@",commandToRun],nil];
    NSLog(@"run command:%@",commandToRun);
    [task setArguments:arguments];

    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput:pipe];

    NSFileHandle *file = [pipe fileHandleForReading];

    [task setQualityOfService:NSQualityOfServiceUserInteractive];
    [task launch];

    NSData *data = [file readDataToEndOfFile];

    NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    const char *cString = [output UTF8String];

同样,这里也需要 15-20 秒来启动脚本或应用程序。

从终端运行脚本需要几毫秒并且不相关。我做了一个实验并创建了非常简单的 Bash 脚本,该脚本将当前日期/秒打印到标准输出:

echo `date`

我测量了 [task launch] 执行和脚本最终启动之间的时间,它总是大约 15-20 秒,即运行非常简单的外部程序总是需要 [task launch] 大量时间.任何线索为什么会这样?这是苹果公证的问题吗?我需要一些特定的权利吗?

17:38:02,075 4353650112 [DEBUG] Execute...
Sun May 16 17:38:18 CEST 2021
done!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...