将简洁的 UNIX IPC 带回 Swift。例如:
guard let inp = Popen(cmd: "/bin/ls /tmp"),
let out = Popen(cmd: "/usr/bin/wc", mode: .write) else {
return XCTFail("Could not open processes")
}
while let line = inp.readLine() {
out.print(line)
}
2.0.0 及以上版本引入了一个封装的 Swift 类,负责在你完成进程后调用 p/fclose()。 还有一个不兼容的更改:从 FILEStream 中读取行作为 Sequence 时,不再包含尾随换行符,使其与 readLine() 方法一致,理由是再次添加比删除它更容易。 添加了新的类 Fopen(),完善了对 stdio 库在 Swift 中使用的探索。
以上代码的旧版本是:
let inp = popen("/bin/ls /tmp", "r")
let out = popen("/usr/bin/wc", "w")
while let line = inp?.readLine() {
out?.print(line)
}
pclose(inp)
pclose(out)
还包括 glob
和 stat
的轻量级封装器。