@@ -183,25 +183,33 @@ class ShizukuBridge(private val context: Context) {
183183 val method = newProcessMethod
184184 ? : return @withContext Result .failure(IllegalStateException (" Shizuku newProcess method unavailable" ))
185185
186+ var process: java.lang.Process ? = null
187+ var timedOut = false
186188 try {
187- withTimeout(timeoutMs) {
188- val process = method.invoke(null , arrayOf(" sh" , " -c" , command), null , null ) as java.lang.Process
189- val reader = BufferedReader (InputStreamReader (process.inputStream))
190- val output = StringBuilder ()
191- var line: String?
192- while (reader.readLine().also { line = it } != null ) {
193- output.append(line).append(" \n " )
194- }
195- reader.close()
196- val exitCode = process.waitFor()
197- if (exitCode == 0 ) {
198- Result .success(output.toString())
199- } else {
200- Result .failure(RuntimeException (" Command failed with exit code $exitCode : $command " ))
201- }
189+ process = method.invoke(null , arrayOf(" sh" , " -c" , " $command 2>/dev/null" ), null , null ) as java.lang.Process
190+ val proc = process
191+ val watchdog = launch {
192+ delay(timeoutMs)
193+ timedOut = true
194+ proc.destroy()
195+ }
196+ val output = try {
197+ proc.inputStream.bufferedReader().use { it.readText() }
198+ } finally {
199+ watchdog.cancel()
200+ }
201+ val exitCode = proc.waitFor()
202+ if (timedOut) {
203+ Result .failure<String >(RuntimeException (" Command timed out after ${timeoutMs} ms: $command " ))
204+ } else if (exitCode == 0 ) {
205+ Result .success(output)
206+ } else {
207+ Result .failure<String >(RuntimeException (" Command failed with exit code $exitCode : $command " ))
202208 }
203209 } catch (e: Throwable ) {
204- Result .failure(e)
210+ Result .failure<String >(e)
211+ } finally {
212+ try { process?.destroy() } catch (_: Throwable ) {}
205213 }
206214 }
207215
0 commit comments