I see you are trying to use sudo to run a bash shell. How are you planning to provide the password when sudo asks for it? That's probably why you think the whole thing is frozen, it's waiting for the password for sudo. So, for this example, it will always "freeze" since it's waiting for a response for the password.
Try using interrupt() instead of terminate() in your background timer.
@jonprescott
sudo -H -u call script from user if you pass this user to function as parameter. This called from root user and password is not required.
I tried to call interrupt - same result :(
I know for sure that the called command frozen. I can debug and I did it for to understand where this is happening. And the called command can actually freeze sometimes.
But the terminate and interrupt - do not kill the process
interrupt() sends a SIGINT (CTRL-C) signal, and terminate() seems to send a SIGTERM signal, based on the documentation hints. Both of those can be be masked off by the spawned process. It seems you need to send something like SIGKILL (kill -9 from the command line) which can't be masked off by the spawned process in your background thread. You can send a SIGKILL using the kill system call (man 2 kill). You will need the process ID (PID) from process, which should be the processIdentifier property for process
A possible problem is that you wait for the process to terminate before reading from the pipe. If the process writes more than what fits into the pipe buffer then you have a deadlock situation.
You might want to read asynchronously from the pipe, e.g. with a readabilityHandler, something like the following (untested) code:
let group = DispatchGroup()
group.enter()
pipe.fileHandleForReading.readabilityHandler = { fh in
let data = fh.availableData
if data.isEmpty { // EOF on the pipe
pipe.fileHandleForReading.readabilityHandler = nil
group.leave()
} else {
result.append(String(data: data, encoding: .utf8)!)
}
}
try process.run()
process.waitUntilExit()
group.wait() // Wait for EOF on the pipe.
no, but I try @jonprescott method with kill -9 and process is not frozen yet.
But it was an issue when the app process stacked but this issue I couldn't reproduce so I made a fix assuming what was the issue.