Hi, I wrote a function that calls linux commands.
But I have a problem, if the called command stacks for some reason, then the swift is waiting for a response and also freezes forever.
I tried to run a timer on a background thread, which after 10 seconds called process.terminate(), but it did not help.
So my app froze forever.
Please help me resolve this problem and kill froze Swift Process.
code:
public func systemCommand(_ command: String, _ user: String? = nil) throws -> String {
var result: String = .init()
let process: Process = .init()
let pipe: Pipe = .init()
process.standardOutput = pipe
process.standardError = pipe
process.executableURL = .init(fileURLWithPath: "/usr/bin/env")
process.arguments = user != nil ? ["sudo", "-H", "-u", user!, "bash", "-lc", "\(command)"] : ["bash", "-lc", "\(command)"]
try process.run()
process.waitUntilExit()
let data: Data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8) {
result = output.trimmingCharacters(in: .whitespacesAndNewlines)
}
if process.isRunning { process.terminate() }
return result
}