使用posix_spawn?

时间:2016-09-15 12:28:56

标签: swift system execute

我尝试从我的应用程序启动一个命令文件,所以我需要使用" posix_spawn"。但是使用它需要奇怪的指针使用。我没有找到任何Swift(3.0)的例子,只有C ++或Objective C我无法翻译。

我只需要这样的东西(在旧的系统调用中):

let err = system("ls -param >file.txt")

有什么想法吗?

编辑: 链接的解决方案并不匹配。 首先,它不使用编译器提到的posix_spawn函数。它使用NSTask,似乎也被放弃了。但我尝试了这个例子并最终进入:

func shell(launchPath: String, arguments: [String]) -> String
{
    let task = Process()
    task.launchPath = launchPath
    task.arguments = arguments

    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String

    return output
}

这里进行了XCode 8所需的所有更改。但是在打电话时,它永远不会从" .launch()"。

返回

在输出调试窗口的某处我找到了这一行:

2016-09-15 15:06:36.793 DSRenamer[96562:2569582] launch path not accessible

相同的命令在终端窗口中正常工作:

/usr/local/bin/ExifTool -ext .CR2

1 个答案:

答案 0 :(得分:0)

我使用swift来调用objective-c menthod(虽然不是最好的方法)

  1. 定义一个objective-c util menthod

    #import "SystemTaskHelper.h"
    @implementation SystemTaskHelper
    +(void)performSystemTask:(NSString *)task
    {
        system([task UTF8String]);
    }
    @end
    
  2. 将objective-c util.h导入Bridging-Header.h,并迅速使用 SystemTaskHelper.performSystemTask("ls -param >file.txt")

相关问题