From b2aa2f8917db3cd1356136dbef96574dc708ee05 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:07:49 -0800 Subject: [PATCH 1/9] ADFA-7178: Stop a plugin's shell command and all it started at its timeout or cancel A timeout could not interrupt the blocking waitFor(), so a hung command was never stopped and await() never returned. A stop killed only the process the IDE held, and the command's children ran on. A background child holding the output kept the call open until the timeout. - Each command runs under setsid, as the leader of a process group of its own. A timeout, cancel() or cancelAllCommands() sends the group SIGTERM, then SIGKILL 250 ms later. - The wait is interruptible and the stop runs in a finally, so it also reaches a process that started while cancel() ran (ADFA-7109). - Once the command exits, its output gets 500 ms to close. A child still holding it is then stopped; a child whose output goes elsewhere is left. - The exit code is read from the process, so a command that exits on its own is never reported as timed out. - The streams are closed after a stop, and the output builders are synchronized between the reader threads and the one ending the command. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- docs/PLUGIN_API_CHANGELOG.md | 9 + .../manager/services/IdeCommandServiceImpl.kt | 194 +++++++----- .../plugins/manager/services/ProcessGroups.kt | 142 +++++++++ .../services/IdeCommandServiceImplTest.kt | 296 +++++++++++++++++- 4 files changed, 561 insertions(+), 80 deletions(-) create mode 100644 plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 1986000ee7..cc396b918c 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -36,6 +36,15 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] = diffed from `plugin-api/src` history (predates the dump; symbol-accurate). ### 26.43 — unreleased +- **breaking — A `ShellCommand` stops at its timeout or `cancel()`, with every process it started** _(ADFA-7178)_ + A timeout used to wait for the command to exit, and a stop killed only the command's own + process, never its children. Each command now runs in a process group of its own, and a + timeout, `cancel()` or `cancelAllCommands()` stops the whole group: SIGTERM, then SIGKILL + 250 ms later. `await()` returns within a second of the timeout, and a stopped command frees its slot. + A command that exits on its own is never reported as timed out. If a background child still + holds its output, `await()` returns 500 ms after the command exits and the child is stopped; + a child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process + that calls `setsid` itself. - **breaking — JavaScript highlighting and the IDE's grammar names are the IDE's** _(ADFA-7084)_ The IDE now highlights `js`, `mjs`, `cjs` and `jsx` itself. A `LanguageDefinition` can still claim them, but only with a language server: its grammar is ignored for them, and its server diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt index 23072e7655..16a5c8909d 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt @@ -7,20 +7,27 @@ import com.itsaky.androidide.plugins.extensions.CommandSpec import com.itsaky.androidide.plugins.services.CommandExecution import com.itsaky.androidide.plugins.services.IdeCommandService import com.itsaky.androidide.utils.TermuxProcessEnvironment +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.runInterruptible +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import java.io.BufferedReader +import java.io.Closeable import java.io.File import java.io.IOException +import java.io.InputStream import java.io.InputStreamReader import java.nio.file.InvalidPathException import java.util.UUID @@ -32,6 +39,7 @@ class IdeCommandServiceImpl internal constructor( private val projectRootProvider: () -> File?, private val appFilesDir: File, private val gradleTaskRunner: GradleTaskRunner = GradleTaskRunner(IdeBuildServiceImpl.getInstance()::startTasks), + private val processGroups: ProcessGroups = ProcessGroups.android, ) : IdeCommandService { private val runningCommands = ConcurrentHashMap() @@ -60,13 +68,14 @@ class IdeCommandServiceImpl internal constructor( } catch (e: IOException) { return RejectedCommandExecution(executionId, "Invalid working directory: ${e.message}") } + val command = processGroups.isolate(listOf(spec.executable) + spec.arguments, workDir) val processBuilder = try { - shellProcess(spec, workDir) + shellProcess(command.command, spec.environment, workDir) } catch (e: IllegalArgumentException) { return RejectedCommandExecution(executionId, "Invalid environment: ${e.message}") } - CommandExecutionImpl(executionId, processBuilder, timeoutMs) + CommandExecutionImpl(executionId, processBuilder::start, command.grouped, processGroups, timeoutMs) } } runningCommands[executionId] = execution @@ -75,12 +84,13 @@ class IdeCommandServiceImpl internal constructor( } private fun shellProcess( - spec: CommandSpec.ShellCommand, + command: List, + environment: Map, workDir: File?, ): ProcessBuilder = - ProcessBuilder(listOf(spec.executable) + spec.arguments).apply { + ProcessBuilder(command).apply { workDir?.let { directory(it) } - environment().putAll(spec.environment) + environment().putAll(environment) redirectErrorStream(false) TermuxProcessEnvironment.applyTo(environment(), appFilesDir) } @@ -131,15 +141,32 @@ internal interface RunningCommand : CommandExecution { fun isRunning(): Boolean } -private class CommandExecutionImpl( +/** + * A shell command. However it ends - on its own, by timing out, by [cancel], or with an error - + * nothing it started is left running and no thread is left reading its output, with two + * exceptions. A command that exits on its own with its output closed may leave a process behind on + * purpose, as `nohup server >log 2>&1 &` does. And a process that left the group with its own + * `setsid` is not stopped; on a desktop JVM, its reader is not freed either. + * + * @param startProcess starts the process, which is the leader of its own process group if [grouped]. + * @param outputGraceMs how long output may stay open once the command has exited. + */ +internal class CommandExecutionImpl( override val executionId: String, - private val processBuilder: ProcessBuilder, + private val startProcess: () -> Process, + private val grouped: Boolean, + private val processGroups: ProcessGroups, private val timeoutMs: Long, + private val outputGraceMs: Long = OUTPUT_GRACE_MS, ) : RunningCommand { private val outputChannel = Channel(capacity = Channel.UNLIMITED) private val resultDeferred = CompletableDeferred() private val scope = CoroutineScope(Dispatchers.IO + Job()) + + @Volatile private var process: Process? = null + + // Appended to by the reader threads, read by whichever thread ends the command. private val stdoutBuilder = StringBuilder() private val stderrBuilder = StringBuilder() @@ -153,89 +180,98 @@ private class CommandExecutionImpl( this.onComplete = onComplete scope.launch { val startTime = System.currentTimeMillis() - - runCatching { - withTimeout(timeoutMs) { - process = processBuilder.start() - val proc = process!! - - val stdoutJob = launch { readStream(proc, isStdErr = false) } - val stderrJob = launch { readStream(proc, isStdErr = true) } - - val exitCode = proc.waitFor() - stdoutJob.join() - stderrJob.join() - - outputChannel.send(CommandOutput.ExitCode(exitCode)) - outputChannel.close() - - val duration = System.currentTimeMillis() - startTime - if (exitCode == 0) { - CommandResult.Success(exitCode, stdoutBuilder.toString(), stderrBuilder.toString(), duration) - } else { - CommandResult.Failure(exitCode, stdoutBuilder.toString(), stderrBuilder.toString(), null, duration) - } + var started: Process? = null + var readers = emptyList() + var exitCode: Int? = null + var outputClosed = false + var cancelled = false + var error: Exception? = null + try { + withTimeoutOrNull(timeoutMs) { + // Recorded before the next suspension point, so that a cancel() landing while + // startProcess() ran, when there was no process yet to stop, has the finally below + // stop it (ADFA-7109). + val proc = startProcess() + started = proc + process = proc + readers = listOf(readLines(proc.inputStream, isStdErr = false), readLines(proc.errorStream, isStdErr = true)) + // Interruptible, so that the timeout and cancel() end the wait at once. + runInterruptible { proc.waitFor() } } - }.onSuccess { result -> - resultDeferred.complete(result) - }.onFailure { e -> - process?.destroyForcibly() - outputChannel.close() - val stdout = stdoutBuilder.toString() - val stderr = stderrBuilder.toString() - val duration = System.currentTimeMillis() - startTime - val failureResult = - when (e) { - is kotlinx.coroutines.TimeoutCancellationException -> { - CommandResult.Failure(-1, stdout, stderr, "Command timed out after ${timeoutMs}ms: ${e.message}", duration) - } - - is kotlinx.coroutines.CancellationException -> { - CommandResult.Cancelled(stdout, stderr) - } - - else -> { - CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${e.message}", duration) - } + // Read from the process, not the block's result: one that exits just as the time runs + // out ended on its own. + exitCode = started?.takeUnless { it.isAlive }?.exitValue() + if (exitCode != null) { + // Not under the timeout: the command has ended. A background child can hold the + // output open long after that, and is then stopped below. + outputClosed = withTimeoutOrNull(outputGraceMs) { readers.joinAll() } != null + } + } catch (e: CancellationException) { + cancelled = true + } catch (e: Exception) { + error = e + } finally { + withContext(NonCancellable) { + started?.let { proc -> + if (exitCode == null || !outputClosed) processGroups.stop(proc, grouped) + // Ends the reads of any process that escaped the group or outlived the kill. + // A desktop JVM, where the unit tests run, does not wake a read on close. + closeQuietly(proc.inputStream, proc.errorStream, proc.outputStream) } - if (resultDeferred.isActive) { - resultDeferred.complete(failureResult) + withTimeoutOrNull(READERS_STOP_MS) { readers.joinAll() } } } + val stdout = snapshot(stdoutBuilder) + val stderr = snapshot(stderrBuilder) + val duration = System.currentTimeMillis() - startTime + val result = + when { + error != null -> CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${error.message}", duration) + exitCode == 0 -> CommandResult.Success(0, stdout, stderr, duration) + exitCode != null -> CommandResult.Failure(exitCode, stdout, stderr, null, duration) + cancelled -> CommandResult.Cancelled(stdout, stderr) + else -> CommandResult.Failure(-1, stdout, stderr, "Command timed out after ${timeoutMs}ms", duration) + } + exitCode?.let { outputChannel.trySend(CommandOutput.ExitCode(it)) } + outputChannel.close() + // cancel() has already completed it with Cancelled. + resultDeferred.complete(result) onComplete() } } - private suspend fun readStream( - process: Process, + private fun readLines( + stream: InputStream, isStdErr: Boolean, - ) { - val stream = if (isStdErr) process.errorStream else process.inputStream - val builder = if (isStdErr) stderrBuilder else stdoutBuilder - BufferedReader(InputStreamReader(stream)).use { reader -> - var line = reader.readLine() - while (line != null) { - if (builder.length + line.length <= MAX_OUTPUT_BYTES) { - builder.appendLine(line) + ): Job = + scope.launch { + val builder = if (isStdErr) stderrBuilder else stdoutBuilder + try { + BufferedReader(InputStreamReader(stream)).use { reader -> + while (true) { + val line = reader.readLine() ?: break + synchronized(builder) { + if (builder.length + line.length <= MAX_OUTPUT_BYTES) builder.appendLine(line) + } + outputChannel.trySend(if (isStdErr) CommandOutput.StdErr(line) else CommandOutput.StdOut(line)) + } } - val output = if (isStdErr) CommandOutput.StdErr(line) else CommandOutput.StdOut(line) - outputChannel.send(output) - line = reader.readLine() + } catch (e: IOException) { + // Closed under the read when the command was stopped. } } - } + + private fun snapshot(builder: StringBuilder): String = synchronized(builder) { builder.toString() } override suspend fun await(): CommandResult = resultDeferred.await() override fun cancel() { - process?.destroyForcibly() outputChannel.close() if (resultDeferred.isActive) { - resultDeferred.complete( - CommandResult.Cancelled(stdoutBuilder.toString(), stderrBuilder.toString()), - ) + resultDeferred.complete(CommandResult.Cancelled(snapshot(stdoutBuilder), snapshot(stderrBuilder))) } + // The command's coroutine stops the process and its group as it ends. scope.cancel() onComplete() } @@ -244,6 +280,22 @@ private class CommandExecutionImpl( companion object { private const val MAX_OUTPUT_BYTES = 10 * 1024 * 1024 + + /** How long output may stay open once the command has exited. */ + const val OUTPUT_GRACE_MS = 500L + + /** How long a reader may take to end once the command is stopped and its output closed. */ + private const val READERS_STOP_MS = 500L + } +} + +private fun closeQuietly(vararg closeables: Closeable) { + for (closeable in closeables) { + try { + closeable.close() + } catch (e: IOException) { + // An InterruptedIOException here (ADFA-3945) only means a read was cut short. + } } } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt new file mode 100644 index 0000000000..9b51dc2eb4 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt @@ -0,0 +1,142 @@ +package com.itsaky.androidide.plugins.manager.services + +import android.system.ErrnoException +import android.system.Os +import android.system.OsConstants +import kotlinx.coroutines.delay +import org.slf4j.LoggerFactory +import java.io.File + +/** A signal [ProcessGroups] sends. [PROBE] delivers nothing; it only asks whether the group exists. */ +internal enum class GroupSignal { PROBE, TERM, KILL } + +/** A command line, and whether it runs as the leader of a process group of its own. */ +internal data class GroupedCommand( + val command: List, + val grouped: Boolean, +) + +/** + * Runs each shell command as the leader of a process group of its own, so that stopping it stops + * every process it started, not only the one the IDE holds. Without a group, a command's children + * (`a | b`, `cmd &`, pip's build steps) outlive it. + * + * @param setsidPath the `setsid` program. It does not fork when its caller leads no group, which a + * [ProcessBuilder] child never does, so the process the IDE holds becomes the group's leader and its + * process id the group's. Null where there is none: commands then share the IDE's group, and only + * their own process can be stopped. + * @param signal sends a [GroupSignal] to every process in group `pgid`, as `kill(-pgid, sig)` does. + * Returns false when no process is left in the group. + */ +internal class ProcessGroups( + private val setsidPath: String?, + private val signal: (pgid: Int, signal: GroupSignal) -> Boolean, +) { + /** [command], changed to run in a group of its own when that is possible. */ + fun isolate( + command: List, + workDir: File?, + ): GroupedCommand { + val setsid = setsidPath ?: return GroupedCommand(command, grouped = false) + // Without the program, start() fails as it always has, rather than setsid failing later. + val program = programPath(command.first(), workDir) ?: return GroupedCommand(command, grouped = false) + return GroupedCommand(listOf(setsid, program) + command.drop(1), grouped = true) + } + + /** + * Stops [process] and, if it is [grouped], every process in its group: SIGTERM first, so a + * command such as pip can clean up, then SIGKILL for whatever is still there [KILL_AFTER_MS] later. + */ + suspend fun stop( + process: Process, + grouped: Boolean, + ) { + val pgid = if (grouped) process.pidOrNull() else null + if (grouped && pgid == null) log.warn("No process id for a command's group; stopping only its own process") + if (pgid != null) { + var left = signal(pgid, GroupSignal.TERM) + // Expected only for a stop landing before setsid ran; otherwise setsid did not make a group. + if (!left && process.isAlive) log.warn("No process group {}; stopping only the command's own process", pgid) + val deadline = System.nanoTime() + KILL_AFTER_MS * NANOS_PER_MILLI + while (left && System.nanoTime() < deadline) { + delay(POLL_MS) + left = signal(pgid, GroupSignal.PROBE) + } + if (left) signal(pgid, GroupSignal.KILL) + } + // Also the whole story where there is no group. + process.destroyForcibly() + } + + companion object { + private val log = LoggerFactory.getLogger(ProcessGroups::class.java) + + const val KILL_AFTER_MS = 250L + private const val POLL_MS = 20L + private const val NANOS_PER_MILLI = 1_000_000L + + private const val ANDROID_SETSID = "/system/bin/setsid" + + /** Android's toybox `setsid`, and `kill(2)` through [Os]. */ + val android: ProcessGroups by lazy { + val setsid = ANDROID_SETSID.takeIf { File(it).canExecute() } + if (setsid == null) log.warn("No {}: a plugin's command can be stopped, but not the processes it starts", ANDROID_SETSID) + ProcessGroups(setsid) { pgid, signal -> + val number = + when (signal) { + GroupSignal.PROBE -> 0 + GroupSignal.TERM -> OsConstants.SIGTERM + GroupSignal.KILL -> OsConstants.SIGKILL + } + try { + Os.kill(-pgid, number) + true + } catch (e: ErrnoException) { + // ESRCH: the group is empty. + false + } + } + } + } +} + +/** + * Where [name] is, as [ProcessBuilder] finds it: a bare name in the IDE's own PATH, which it uses + * rather than the command's. `setsid` would search the command's, which puts Termux's first, so it + * is given the path. Null if there is no such program. + */ +private fun programPath( + name: String, + workDir: File?, +): String? { + val file = + when { + '/' !in name -> { + System + .getenv("PATH") + .orEmpty() + .split(':') + .filter { it.isNotEmpty() } + .map { File(it, name) } + .firstOrNull { it.isFile && it.canExecute() } + } + + File(name).isAbsolute -> { + File(name) + } + + else -> { + File(workDir ?: File("").absoluteFile, name) + } + } + return file?.takeIf { it.isFile && it.canExecute() }?.absolutePath +} + +/** + * The process id, which Android's API does not offer. Android's process class keeps it in a `pid` + * field, which Termux's `ShellUtils.getPid` reads too; a desktop JVM, where the unit tests run, has + * the `pid()` method instead. + */ +private fun Process.pidOrNull(): Int? = + runCatching { javaClass.getDeclaredField("pid").apply { isAccessible = true }.getInt(this) }.getOrNull() + ?: runCatching { (Process::class.java.getMethod("pid").invoke(this) as Long).toInt() }.getOrNull() diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt index ecbb1c891d..ae9d7b172c 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt @@ -4,31 +4,122 @@ import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.plugins.PluginPermission import com.itsaky.androidide.plugins.extensions.CommandResult import com.itsaky.androidide.plugins.extensions.CommandSpec +import com.itsaky.androidide.plugins.services.CommandExecution import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertThrows +import org.junit.Assume.assumeTrue import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import java.io.File +import java.util.concurrent.CountDownLatch class IdeCommandServiceImplTest { @get:Rule val tmp = TemporaryFolder() + private val projectRoot by lazy { tmp.newFolder("project") } + private val filesDir by lazy { tmp.newFolder("files") } + private val pidFile by lazy { File(tmp.root, "pids") } + + /** `setsid` and `kill` from util-linux and procps, standing in for Android's toybox and [android.system.Os]. */ + private val hostGroups = + ProcessGroups(SETSID) { pgid, signal -> + val name = + when (signal) { + GroupSignal.PROBE -> "0" + GroupSignal.TERM -> "TERM" + GroupSignal.KILL -> "KILL" + } + ProcessBuilder(KILL, "-s", name, "--", "-$pgid") + .redirectOutput(DEV_NULL) + .redirectError(DEV_NULL) + .start() + .waitFor() == 0 + } + + @After + fun killLeftovers() { + if (pidFile.exists()) { + for (pid in pidFile.readLines().mapNotNull { it.trim().toIntOrNull() }) { + ProcessBuilder(KILL, "-s", "KILL", "$pid").start().waitFor() + } + } + // A cancel returns before its readers end, so they must not count against the next test. + val deadline = System.currentTimeMillis() + 2_000 + while (readerThreads().isNotEmpty() && System.currentTimeMillis() < deadline) Thread.sleep(10) + } + + private fun service(processGroups: ProcessGroups = hostGroups) = + IdeCommandServiceImpl( + pluginId = "test.plugin", + permissions = setOf(PluginPermission.SYSTEM_COMMANDS), + projectRootProvider = { projectRoot }, + appFilesDir = filesDir, + processGroups = processGroups, + ) + private fun resultFor(workingDirectory: String): CommandResult = resultFor(CommandSpec.ShellCommand("true", workingDirectory = workingDirectory)) private fun resultFor(spec: CommandSpec): CommandResult { - val projectRoot = tmp.newFolder("project") - val service = - IdeCommandServiceImpl( - pluginId = "test.plugin", - permissions = setOf(PluginPermission.SYSTEM_COMMANDS), - projectRootProvider = { projectRoot }, - appFilesDir = tmp.newFolder("files"), - ) - val execution = service.executeCommand(spec, 5_000) + val execution = service(ProcessGroups.android).executeCommand(spec, 5_000) return runBlocking { execution.await() } } + /** `sh -c [script]`, where `$1` is [pidFile] for the script to write the ids of its processes to. */ + private fun shell(script: String) = CommandSpec.ShellCommand("sh", listOf("-c", script, "sh", pidFile.path)) + + private fun CommandExecution.awaitWithin(ms: Long): CommandResult = runBlocking { withTimeout(ms) { await() } } + + /** The [count] process ids the command wrote to [pidFile], once it has written them. */ + private fun pids(count: Int): List { + val deadline = System.currentTimeMillis() + 5_000 + while (System.currentTimeMillis() < deadline) { + val pids = if (pidFile.exists()) pidFile.readLines().mapNotNull { it.trim().toIntOrNull() } else emptyList() + if (pids.size >= count) return pids + Thread.sleep(10) + } + throw AssertionError("the command wrote no $count process ids to $pidFile") + } + + private fun alive(pid: Int): Boolean { + val stat = File("/proc/$pid/stat").takeIf { it.exists() }?.runCatching { readText() }?.getOrNull() ?: return false + // The state follows the parenthesised name; a zombie has exited. + return stat.substringAfterLast(") ").first() !in "ZX" + } + + /** Whether every process in [pids] is gone within [ms]. */ + private fun goneWithin( + pids: List, + ms: Long, + ): Boolean { + val deadline = System.currentTimeMillis() + ms + while (pids.any(::alive)) { + if (System.currentTimeMillis() > deadline) return false + Thread.sleep(10) + } + return true + } + + /** Threads still in a command's output reader. */ + private fun readerThreads(): List { + val reader = "${CommandExecutionImpl::class.java.name}\$readLines" + return Thread + .getAllStackTraces() + .filterValues { frames -> frames.any { it.className.startsWith(reader) } } + .keys + .map { it.name } + } + + private fun assumeHostTools() = + assumeTrue( + "needs util-linux setsid and procps kill", + File(SETSID).canExecute() && File(KILL).canExecute(), + ) + @Test fun `a working directory with a NUL character fails the command`() { val result = resultFor("sub\u0000dir") @@ -52,4 +143,191 @@ class IdeCommandServiceImplTest { assertThat(result).isInstanceOf(CommandResult.Failure::class.java) assertThat((result as CommandResult.Failure).error).startsWith("Invalid environment") } + + @Test + fun `a command past its timeout is stopped with every process it started`() { + assumeHostTools() + val started = System.currentTimeMillis() + + val result = service().executeCommand(shell(CHILDREN_SCRIPT), 1_000).awaitWithin(10_000) + + assertThat(System.currentTimeMillis() - started).isLessThan(2_000) + assertThat(result).isInstanceOf(CommandResult.Failure::class.java) + assertThat((result as CommandResult.Failure).error).isEqualTo("Command timed out after 1000ms") + assertThat(pids(CHILDREN_SCRIPT_PIDS).filter(::alive)).isEmpty() + assertThat(readerThreads()).isEmpty() + } + + @Test + fun `cancel stops the command and every process it started`() { + assumeHostTools() + val execution = service().executeCommand(shell(CHILDREN_SCRIPT), 60_000) + val pids = pids(CHILDREN_SCRIPT_PIDS) + + execution.cancel() + + assertThat(execution.awaitWithin(1_000)).isInstanceOf(CommandResult.Cancelled::class.java) + assertThat(goneWithin(pids, 1_000)).isTrue() + } + + @Test + fun `cancel while the process is starting stops it once it has started`() { + assumeHostTools() + val starting = CountDownLatch(1) + val release = CountDownLatch(1) + val script = "sleep 600 & echo \$! >> \"\$1\"; echo \$\$ >> \"\$1\"; wait" + val execution = + CommandExecutionImpl( + "test", + { + starting.countDown() + release.await() + // Returns once the command has started a child, so that a stop must reach both. + ProcessBuilder(SETSID, "sh", "-c", script, "sh", pidFile.path).start().also { pids(2) } + }, + grouped = true, + processGroups = hostGroups, + timeoutMs = 60_000, + ) + execution.start {} + starting.await() + + execution.cancel() + release.countDown() + + assertThat(goneWithin(pids(2), 1_000)).isTrue() + } + + @Test + fun `cancelAllCommands stops every process the commands started`() { + assumeHostTools() + val service = service() + service.executeCommand(shell(CHILDREN_SCRIPT), 60_000) + val pids = pids(CHILDREN_SCRIPT_PIDS) + + service.cancelAllCommands() + + assertThat(goneWithin(pids, 1_000)).isTrue() + assertThat(service.getRunningCommandCount()).isEqualTo(0) + } + + @Test + fun `a command that exits before its timeout is not timed out while a child holds its output`() { + assumeHostTools() + val script = "echo done; sleep 600 & echo \$! >> \"\$1\"" + // The output stays open past the 1 s limit, until the grace ends and the child is stopped. + val execution = + CommandExecutionImpl( + "test", + ProcessBuilder(SETSID, "sh", "-c", script, "sh", pidFile.path)::start, + grouped = true, + processGroups = hostGroups, + timeoutMs = 1_000, + outputGraceMs = 2_000, + ) + execution.start {} + + val result = execution.awaitWithin(10_000) + + assertThat(result).isEqualTo(CommandResult.Success(0, "done\n", "", (result as CommandResult.Success).durationMs)) + assertThat(result.durationMs).isAtLeast(2_000) + assertThat(pids(1).filter(::alive)).isEmpty() + } + + @Test + fun `a process that ignores SIGTERM is killed`() { + assumeHostTools() + // The ignored TERM is inherited by the shell's child. + val script = "trap '' TERM; echo \$\$ >> \"\$1\"; sleep 600 & echo \$! >> \"\$1\"; wait" + + val result = service().executeCommand(shell(script), 300).awaitWithin(10_000) + + assertThat((result as CommandResult.Failure).error).isEqualTo("Command timed out after 300ms") + assertThat(goneWithin(pids(2), 1_000)).isTrue() + } + + @Test + fun `a command returns soon after it exits though a child holds its output`() { + assumeHostTools() + val started = System.currentTimeMillis() + + val result = service().executeCommand(shell("echo done; sleep 600 & echo \$! >> \"\$1\""), 60_000).awaitWithin(10_000) + + assertThat(System.currentTimeMillis() - started).isLessThan(CommandExecutionImpl.OUTPUT_GRACE_MS + 1_000) + assertThat(result).isInstanceOf(CommandResult.Success::class.java) + assertThat((result as CommandResult.Success).stdout).isEqualTo("done\n") + assertThat(readerThreads()).isEmpty() + assertThat(pids(1).filter(::alive)).isEmpty() + } + + @Test + fun `a command that exits with its output closed may leave a process running`() { + assumeHostTools() + + val result = service().executeCommand(shell("sleep 600 >/dev/null 2>&1 & echo \$! >> \"\$1\""), 60_000).awaitWithin(10_000) + + assertThat(result).isInstanceOf(CommandResult.Success::class.java) + assertThat(pids(1).filter(::alive)).hasSize(1) + } + + @Test + fun `stopped commands free their slots`() { + assumeHostTools() + val service = service() + val timedOut = List(3) { service.executeCommand(shell("sleep 600"), 300) } + assertThrows(IllegalStateException::class.java) { service.executeCommand(shell("true"), 300) } + + timedOut.forEach { it.awaitWithin(10_000) } + val deadline = System.currentTimeMillis() + 1_000 + while (service.getRunningCommandCount() > 0 && System.currentTimeMillis() < deadline) Thread.sleep(10) + val cancelled = List(3) { service.executeCommand(shell("sleep 600"), 60_000) } + cancelled.forEach { service.cancelCommand(it.executionId) } + + assertThat(service.getRunningCommandCount()).isEqualTo(0) + assertThat(service.executeCommand(shell("true"), 5_000).awaitWithin(5_000)).isInstanceOf(CommandResult.Success::class.java) + } + + @Test + fun `without setsid a timeout still stops the command itself`() { + assumeHostTools() + val noGroups = ProcessGroups(null) { _, _ -> throw AssertionError("signalled a group that does not exist") } + + val result = service(noGroups).executeCommand(shell("echo \$\$ >> \"\$1\"; exec sleep 600"), 300).awaitWithin(10_000) + + assertThat((result as CommandResult.Failure).error).isEqualTo("Command timed out after 300ms") + assertThat(goneWithin(pids(1), 1_000)).isTrue() + } + + @Test + fun `a command runs in a group of its own when setsid can run it`() { + val command = ProcessGroups("/setsid") { _, _ -> true }.isolate(listOf("sh", "-c", "true"), null) + + assertThat(command.grouped).isTrue() + assertThat(command.command[0]).isEqualTo("/setsid") + // The sh ProcessBuilder would run, found in the IDE's PATH rather than the command's. + assertThat(File(command.command[1]).isAbsolute).isTrue() + assertThat(File(command.command[1]).name).isEqualTo("sh") + assertThat(command.command.drop(2)).containsExactly("-c", "true").inOrder() + } + + @Test + fun `a command with no such program is left to fail as before`() { + val command = listOf("no-such-program-7178", "x") + + val isolated = ProcessGroups("/setsid") { _, _ -> true }.isolate(command, null) + + assertThat(isolated).isEqualTo(GroupedCommand(command, grouped = false)) + } + + private companion object { + const val SETSID = "/usr/bin/setsid" + const val KILL = "/usr/bin/kill" + val DEV_NULL = File("/dev/null") + + /** A child, a double-forked grandchild, the shell itself, and a child it waits for. */ + const val CHILDREN_SCRIPT = + "sleep 600 & echo \$! >> \"\$1\"; (sleep 600 & echo \$! >> \"\$1\"); " + + "echo \$\$ >> \"\$1\"; sleep 600 & echo \$! >> \"\$1\"; wait" + const val CHILDREN_SCRIPT_PIDS = 4 + } } From 6b5ecbaf8511583c35a85fae99f54d6c06e47f5f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:07:49 -0800 Subject: [PATCH 2/9] ADFA-7178: Show control characters in a plugin's Terminal command line agent-run.sh echoed the command line raw, so a control character in it reached the terminal emulator: OSC 52 could set the clipboard, and a CR could hide part of the echo. AgentRunner now writes a display copy with C0 (but tab and newline), DEL and C1 characters as , and the script prints that copy. The command that runs is unchanged. bash's own message for a syntax error quotes the command raw too, so the script now checks the syntax with bash -n first. On an error it prints the message with control characters replaced by '?' and exits 2, as eval would, without running anything. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../itsaky/androidide/terminal/AgentRunner.kt | 25 ++++++- .../itsaky/androidide/terminal/agent-run.sh | 13 +++- .../androidide/terminal/AgentRunnerTest.kt | 66 ++++++++++++++++--- 3 files changed, 91 insertions(+), 13 deletions(-) diff --git a/termux/termux-app/src/main/java/com/itsaky/androidide/terminal/AgentRunner.kt b/termux/termux-app/src/main/java/com/itsaky/androidide/terminal/AgentRunner.kt index 7a9ac7a9b1..063f5f8302 100644 --- a/termux/termux-app/src/main/java/com/itsaky/androidide/terminal/AgentRunner.kt +++ b/termux/termux-app/src/main/java/com/itsaky/androidide/terminal/AgentRunner.kt @@ -33,6 +33,7 @@ class AgentRunner( directory.mkdirs() installScript() File(directory, "$id.cmd").writeText(command) + File(directory, "$id.show").writeText(displayed(command)) File(directory, "$id.dir").writeText(workingDirectory.orEmpty()) return id } @@ -57,7 +58,7 @@ class AgentRunner( * * @return true if taken back; false if the runner took it first, or it was never prepared. */ - fun withdraw(id: String): Boolean = File(directory, "$id.cmd").delete().also { if (it) File(directory, "$id.dir").delete() } + fun withdraw(id: String): Boolean = File(directory, "$id.cmd").delete().also { if (it) deleteCompanions(id) } /** * Deletes the files of command [id], which will never run; the runner deletes them once it @@ -65,6 +66,11 @@ class AgentRunner( */ fun discard(id: String) { File(directory, "$id.cmd").delete() + deleteCompanions(id) + } + + private fun deleteCompanions(id: String) { + File(directory, "$id.show").delete() File(directory, "$id.dir").delete() } @@ -94,6 +100,23 @@ class AgentRunner( /** Runs commands from Termux's tmp directory, which Termux clears when its service stops. */ val termux = AgentRunner(File(TermuxConstants.TERMUX_TMP_PREFIX_DIR_PATH)) + + /** + * [command] as the session shows it before running it: each control character but tab and + * newline written as ``. Printed raw, a value in a plugin's command line would drive + * the terminal: OSC 52 sets the clipboard, and a CR or a cursor move rewrites the echo. + */ + internal fun displayed(command: String): String = + buildString { + for (c in command) { + val control = c < ' ' || c in '\u007f'..'\u009f' // C0, DEL and C1 + if (control && c != '\t' && c != '\n') { + append("') + } else { + append(c) + } + } + } } } diff --git a/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh b/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh index 8aec84d8d6..393ad8ca0b 100644 --- a/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh +++ b/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh @@ -20,10 +20,19 @@ trap 'mark "D;$?"' EXIT mv -- "$dir/$id.cmd" "$dir/$id.run" 2>/dev/null || exit 1 cmd=$(cat "$dir/$id.run") || exit 1 wd=$(cat "$dir/$id.dir") || exit 1 -rm -f "$dir/$id.run" "$dir/$id.dir" +# The command as shown: AgentRunner made its control characters visible, which printed raw would +# drive the terminal. +shown=$(cat "$dir/$id.show") || exit 1 +rm -f "$dir/$id.run" "$dir/$id.dir" "$dir/$id.show" mark C -printf '$ %s\n' "$cmd" +printf '$ %s\n' "$shown" cd -- "${wd:-$HOME}" || exit 1 +# A syntax error message quotes the command raw, so the syntax is checked first and an error is +# shown with its control characters replaced. Exits 2, as eval does on a syntax error. +if ! err=$(bash -n -c "$cmd" 2>&1); then + while IFS= read -r line; do printf '%s\n' "${line//[[:cntrl:]]/?}"; done <<<"$err" >&2 + exit 2 +fi # In a subshell, so an exec or a trap in the command cannot take the EXIT trap with it. (eval "$cmd") diff --git a/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt b/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt index 22d22e99cd..1cd09819c7 100644 --- a/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt +++ b/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt @@ -31,20 +31,21 @@ class AgentRunnerTest { val output: String, ) - private fun run(id: String): Run { + /** What the runner writes to the terminal for command [id], before the terminal reads it. */ + private fun rawOutput(id: String): String { val process = ProcessBuilder(BASH, File(tmp.root, "agent-run").path, id) .apply { environment()["HOME"] = tmp.root.path } .redirectErrorStream(true) .start() - // A pty turns \n into \r\n on the way out; the pipe here does not. - val bytes = - process.inputStream - .readBytes() - .toString(Charsets.UTF_8) - .replace("\n", "\r\n") - .toByteArray() + val output = process.inputStream.readBytes().toString(Charsets.UTF_8) process.waitFor() + return output + } + + private fun run(id: String): Run { + // A pty turns \n into \r\n on the way out; the pipe here does not. + val bytes = rawOutput(id).replace("\n", "\r\n").toByteArray() val marks = mutableListOf() lateinit var terminal: TerminalEmulator @@ -98,6 +99,52 @@ class AgentRunnerTest { assertThat(run.output).isEqualTo("\$ echo \"it's quoted\"; exit 3\nit's quoted") } + @Test + fun controlCharactersInTheCommandAreEchoedVisiblyAndRunUnchanged() { + val out = File(tmp.root, "out") + // Printed raw, the OSC 52 would put "PWNED", base64-encoded here, on the clipboard. + val id = runner.prepare(": '\u001b]52;c;UFdORUQ=\u0007'; printf '%s' 'a\rb\u009bc' > ${out.path}", null) + + val output = rawOutput(id) + + assertThat(output).doesNotContain("\u001b]52") + assertThat(output).contains("\$ : ']52;c;UFdORUQ='; printf '%s' 'abc' > ${out.path}\n") + assertThat(out.readText()).isEqualTo("a\rb\u009bc") + } + + @Test + fun syntaxErrorIsReportedWithoutItsControlCharactersAndNothingRuns() { + val out = File(tmp.root, "out") + // bash quotes the line of a syntax error in its message, OSC 52 and all. + val id = runner.prepare("touch ${out.path}; echo '\u001b]52;c;UFdORUQ=\u0007' (", null) + + val output = rawOutput(id) + + // The runner's own marks are the only control sequences left. + val text = output.replace(Regex("\u001b]133;[^\u0007]*\u0007"), "") + assertThat(text).doesNotContain("\u001b") + assertThat(text).doesNotContain("\u0007") + assertThat(text).contains("?]52;c;UFdORUQ=?") + assertThat(output).contains("\u001b]133;D;2;") + assertThat(out.exists()).isFalse() + } + + @Test + fun carriageReturnInTheCommandCannotRewriteItsEcho() { + // Printed raw, the CR would return to the start of the line, and the echo would show only + // what follows it. + val run = run(runner.prepare(": 'rm -rf ~'\r: 'harmless'", null)) + + assertThat(run.output.lines().first()).isEqualTo("\$ : 'rm -rf ~': 'harmless'") + assertThat(run.marks.last().exitCode).isEqualTo(0) + } + + @Test + fun displayedCommandMakesOnlyControlCharactersVisible() { + assertThat(AgentRunner.displayed("a\u0000b\u001bc\u007fd\u0080e\u009ff\u00a0g\th\ni\u00e9\u2028")) + .isEqualTo("abcdef\u00a0g\th\ni\u00e9\u2028") + } + @Test fun commandRunsInItsWorkingDirectory() { val dir = tmp.newFolder("project") @@ -178,8 +225,7 @@ class AgentRunnerTest { runner.discard(id) - assertThat(File(tmp.root, "$id.cmd").exists()).isFalse() - assertThat(File(tmp.root, "$id.dir").exists()).isFalse() + assertThat(tmp.root.list()).asList().containsExactly("agent-run") } @Test From 62493426f017939b76024a8d24a8ad7e7693b402 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 12:42:07 -0800 Subject: [PATCH 3/9] ADFA-7178: Check a plugin's Terminal command with extglob on The syntax check in agent-run.sh refused a valid command that turns on extglob on one line and uses it on the next. eval runs a command's lines one at a time, so the shopt applies before the next line is parsed, but bash -n runs nothing. The check now runs with extglob on. Also states how long await() takes when a background child holds the output, and checks a test's stdout directly instead of comparing with a value taken from the result itself. Raised by an independent review of 6b5ecbaf8. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- docs/PLUGIN_API_CHANGELOG.md | 4 ++-- .../plugins/manager/services/IdeCommandServiceImplTest.kt | 4 +++- .../resources/com/itsaky/androidide/terminal/agent-run.sh | 6 ++++-- .../com/itsaky/androidide/terminal/AgentRunnerTest.kt | 8 ++++++++ 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index cc396b918c..5b96091843 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -42,8 +42,8 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] timeout, `cancel()` or `cancelAllCommands()` stops the whole group: SIGTERM, then SIGKILL 250 ms later. `await()` returns within a second of the timeout, and a stopped command frees its slot. A command that exits on its own is never reported as timed out. If a background child still - holds its output, `await()` returns 500 ms after the command exits and the child is stopped; - a child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process + holds its output 500 ms after the command exits, the child is stopped, and `await()` returns + within about 1.5 s of the exit; a child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process that calls `setsid` itself. - **breaking — JavaScript highlighting and the IDE's grammar names are the IDE's** _(ADFA-7084)_ The IDE now highlights `js`, `mjs`, `cjs` and `jsx` itself. A `LanguageDefinition` can still diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt index ae9d7b172c..3847272713 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt @@ -229,7 +229,9 @@ class IdeCommandServiceImplTest { val result = execution.awaitWithin(10_000) - assertThat(result).isEqualTo(CommandResult.Success(0, "done\n", "", (result as CommandResult.Success).durationMs)) + assertThat(result).isInstanceOf(CommandResult.Success::class.java) + result as CommandResult.Success + assertThat(result.stdout).isEqualTo("done\n") assertThat(result.durationMs).isAtLeast(2_000) assertThat(pids(1).filter(::alive)).isEmpty() } diff --git a/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh b/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh index 393ad8ca0b..56442ae56e 100644 --- a/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh +++ b/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh @@ -29,8 +29,10 @@ mark C printf '$ %s\n' "$shown" cd -- "${wd:-$HOME}" || exit 1 # A syntax error message quotes the command raw, so the syntax is checked first and an error is -# shown with its control characters replaced. Exits 2, as eval does on a syntax error. -if ! err=$(bash -n -c "$cmd" 2>&1); then +# shown with its control characters replaced. Exits 2, as eval does on a syntax error. The check +# has extglob on: eval runs a command's lines one at a time, so a "shopt -s extglob" on one line +# applies to the next, but -n runs nothing. +if ! err=$(bash -O extglob -n -c "$cmd" 2>&1); then while IFS= read -r line; do printf '%s\n' "${line//[[:cntrl:]]/?}"; done <<<"$err" >&2 exit 2 fi diff --git a/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt b/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt index 1cd09819c7..d437670e80 100644 --- a/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt +++ b/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt @@ -129,6 +129,14 @@ class AgentRunnerTest { assertThat(out.exists()).isFalse() } + @Test + fun commandThatTurnsOnExtglobBeforeUsingItRuns() { + val run = run(runner.prepare("shopt -s extglob\ncase ab in +(a|b)) echo matched;; esac", null)) + + assertThat(run.output.lines().last()).isEqualTo("matched") + assertThat(run.marks.last().exitCode).isEqualTo(0) + } + @Test fun carriageReturnInTheCommandCannotRewriteItsEcho() { // Printed raw, the CR would return to the start of the line, and the echo would show only From f1d9248ff3c08ef2b9b18c4a379c54fc85847547 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 13:26:18 -0800 Subject: [PATCH 4/9] ADFA-7178: Group commands only where setsid runs them in place Android 11's toybox setsid makes itself a group leader before calling setsid(), so setsid() always fails, and it forks and exits 0 at once. There every command would have seemed to succeed within the 500 ms output grace, with its output cut short, while it ran on in a group the IDE does not hold. The IDE now checks setsid once, by running sh under it and comparing the pid sh prints with the one it holds, and runs commands without a group where they differ, as before this change. A finished or cancelled command now frees its slot before await() returns, so a caller that starts the next command at once is not refused. Also restores a test's stderr check, and notes in agent-run.sh that the extglob syntax check passes an extglob pattern a command never turns on. Raised by CodeRabbit's review of 62493426f and an independent review. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- docs/PLUGIN_API_CHANGELOG.md | 2 + .../manager/services/IdeCommandServiceImpl.kt | 6 +- .../plugins/manager/services/ProcessGroups.kt | 45 ++++++++-- .../services/IdeCommandServiceImplTest.kt | 90 ++++++++++++++++--- .../itsaky/androidide/terminal/agent-run.sh | 3 +- 5 files changed, 121 insertions(+), 25 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 5b96091843..e65594e3bb 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -41,6 +41,8 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] process, never its children. Each command now runs in a process group of its own, and a timeout, `cancel()` or `cancelAllCommands()` stops the whole group: SIGTERM, then SIGKILL 250 ms later. `await()` returns within a second of the timeout, and a stopped command frees its slot. + On Android 11, whose `setsid` always forks, commands get no group of their own, and a stop + reaches only the command's own process, as before. A command that exits on its own is never reported as timed out. If a background child still holds its output 500 ms after the command exits, the child is stopped, and `await()` returns within about 1.5 s of the exit; a child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt index 16a5c8909d..19c902e734 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt @@ -235,9 +235,10 @@ internal class CommandExecutionImpl( } exitCode?.let { outputChannel.trySend(CommandOutput.ExitCode(it)) } outputChannel.close() + // First, so that a caller resuming from await() finds the slot free. + onComplete() // cancel() has already completed it with Cancelled. resultDeferred.complete(result) - onComplete() } } @@ -268,12 +269,13 @@ internal class CommandExecutionImpl( override fun cancel() { outputChannel.close() + // First, so that a caller resuming from await() finds the slot free. + onComplete() if (resultDeferred.isActive) { resultDeferred.complete(CommandResult.Cancelled(snapshot(stdoutBuilder), snapshot(stderrBuilder))) } // The command's coroutine stops the process and its group as it ends. scope.cancel() - onComplete() } override fun isRunning(): Boolean = process?.isAlive == true diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt index 9b51dc2eb4..2f24d7cd3a 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt @@ -6,6 +6,7 @@ import android.system.OsConstants import kotlinx.coroutines.delay import org.slf4j.LoggerFactory import java.io.File +import java.util.concurrent.TimeUnit /** A signal [ProcessGroups] sends. [PROBE] delivers nothing; it only asks whether the group exists. */ internal enum class GroupSignal { PROBE, TERM, KILL } @@ -21,10 +22,9 @@ internal data class GroupedCommand( * every process it started, not only the one the IDE holds. Without a group, a command's children * (`a | b`, `cmd &`, pip's build steps) outlive it. * - * @param setsidPath the `setsid` program. It does not fork when its caller leads no group, which a - * [ProcessBuilder] child never does, so the process the IDE holds becomes the group's leader and its - * process id the group's. Null where there is none: commands then share the IDE's group, and only - * their own process can be stopped. + * @param setsidPath the `setsid` program, one that runs its command in place (see [usableSetsid]), so + * the process the IDE holds becomes the group's leader and its process id the group's. Null where + * there is none: commands then share the IDE's group, and only their own process can be stopped. * @param signal sends a [GroupSignal] to every process in group `pgid`, as `kill(-pgid, sig)` does. * Returns false when no process is left in the group. */ @@ -76,12 +76,12 @@ internal class ProcessGroups( private const val NANOS_PER_MILLI = 1_000_000L private const val ANDROID_SETSID = "/system/bin/setsid" + private const val ANDROID_SH = "/system/bin/sh" + private const val CHECK_TIMEOUT_S = 5L - /** Android's toybox `setsid`, and `kill(2)` through [Os]. */ + /** Android's toybox `setsid`, if it runs commands in place, and `kill(2)` through [Os]. */ val android: ProcessGroups by lazy { - val setsid = ANDROID_SETSID.takeIf { File(it).canExecute() } - if (setsid == null) log.warn("No {}: a plugin's command can be stopped, but not the processes it starts", ANDROID_SETSID) - ProcessGroups(setsid) { pgid, signal -> + ProcessGroups(usableSetsid(ANDROID_SETSID, ANDROID_SH)) { pgid, signal -> val number = when (signal) { GroupSignal.PROBE -> 0 @@ -97,6 +97,35 @@ internal class ProcessGroups( } } } + + /** + * [setsid] if it runs its command in place, which it checks by running [shell] under it once; + * otherwise null, with a warning. Toybox's `setsid` forks only when its caller leads a group, + * which a [ProcessBuilder] child never does, except in Android 11: there it makes itself a + * group leader first, so it always forks and exits 0 at once. Every command would then seem to + * end as it started, and its group would not be the one the IDE holds. + */ + fun usableSetsid( + setsid: String, + shell: String, + ): String? { + if (!File(setsid).canExecute()) { + log.warn("No {}: a plugin's command can be stopped, but not the processes it starts", setsid) + return null + } + val inPlace = + runCatching { + val process = ProcessBuilder(setsid, shell, "-c", "echo \$\$").redirectErrorStream(true).start() + if (!process.waitFor(CHECK_TIMEOUT_S, TimeUnit.SECONDS)) { + process.destroyForcibly() + return@runCatching false + } + val printed = process.inputStream.bufferedReader().use { it.readLine() } + printed != null && printed.trim() == process.pidOrNull()?.toString() + }.getOrDefault(false) + if (!inPlace) log.warn("{} forks: a plugin's command can be stopped, but not the processes it starts", setsid) + return setsid.takeIf { inPlace } + } } } diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt index 3847272713..40fb6d39ea 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt @@ -5,6 +5,8 @@ import com.itsaky.androidide.plugins.PluginPermission import com.itsaky.androidide.plugins.extensions.CommandResult import com.itsaky.androidide.plugins.extensions.CommandSpec import com.itsaky.androidide.plugins.services.CommandExecution +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import org.junit.After @@ -25,20 +27,24 @@ class IdeCommandServiceImplTest { private val pidFile by lazy { File(tmp.root, "pids") } /** `setsid` and `kill` from util-linux and procps, standing in for Android's toybox and [android.system.Os]. */ - private val hostGroups = - ProcessGroups(SETSID) { pgid, signal -> - val name = - when (signal) { - GroupSignal.PROBE -> "0" - GroupSignal.TERM -> "TERM" - GroupSignal.KILL -> "KILL" - } - ProcessBuilder(KILL, "-s", name, "--", "-$pgid") - .redirectOutput(DEV_NULL) - .redirectError(DEV_NULL) - .start() - .waitFor() == 0 - } + private val hostGroups = ProcessGroups(SETSID, ::hostSignal) + + private fun hostSignal( + pgid: Int, + signal: GroupSignal, + ): Boolean { + val name = + when (signal) { + GroupSignal.PROBE -> "0" + GroupSignal.TERM -> "TERM" + GroupSignal.KILL -> "KILL" + } + return ProcessBuilder(KILL, "-s", name, "--", "-$pgid") + .redirectOutput(DEV_NULL) + .redirectError(DEV_NULL) + .start() + .waitFor() == 0 + } @After fun killLeftovers() { @@ -232,6 +238,7 @@ class IdeCommandServiceImplTest { assertThat(result).isInstanceOf(CommandResult.Success::class.java) result as CommandResult.Success assertThat(result.stdout).isEqualTo("done\n") + assertThat(result.stderr).isEmpty() assertThat(result.durationMs).isAtLeast(2_000) assertThat(pids(1).filter(::alive)).isEmpty() } @@ -289,6 +296,60 @@ class IdeCommandServiceImplTest { assertThat(service.executeCommand(shell("true"), 5_000).awaitWithin(5_000)).isInstanceOf(CommandResult.Success::class.java) } + @Test + fun `a command's slot is free once its await returns`() { + assumeHostTools() + val service = service() + val running = mutableListOf() + + runBlocking { + // Unconfined: the code after await() runs inside the completion, as soon as the result is set. + val finished = service.executeCommand(shell("sleep 0.2"), 5_000) + launch(Dispatchers.Unconfined) { + finished.await() + running += service.getRunningCommandCount() + }.join() + val cancelled = service.executeCommand(shell("sleep 600"), 60_000) + val waiter = + launch(Dispatchers.Unconfined) { + cancelled.await() + running += service.getRunningCommandCount() + } + cancelled.cancel() + waiter.join() + } + + assertThat(running).containsExactly(0, 0) + } + + @Test + fun `setsid is used when it runs the command in place`() { + assumeHostTools() + + assertThat(ProcessGroups.usableSetsid(SETSID, SH)).isEqualTo(SETSID) + } + + @Test + fun `a missing setsid is not used`() { + assertThat(ProcessGroups.usableSetsid(File(tmp.root, "none").path, SH)).isNull() + } + + // As Android 11's toybox setsid does: it forks, and its parent exits 0 at once. + @Test + fun `a setsid that forks is not used, so a command still runs to its end`() { + assumeHostTools() + val forking = + File(tmp.root, "setsid").apply { + writeText("#!/bin/sh\n\"\$@\" &\nexit 0\n") + setExecutable(true) + } + val groups = ProcessGroups(ProcessGroups.usableSetsid(forking.path, SH), ::hostSignal) + + val result = service(groups).executeCommand(shell("sleep 1; echo late"), 10_000).awaitWithin(10_000) + + assertThat((result as CommandResult.Success).stdout).isEqualTo("late\n") + } + @Test fun `without setsid a timeout still stops the command itself`() { assumeHostTools() @@ -324,6 +385,7 @@ class IdeCommandServiceImplTest { private companion object { const val SETSID = "/usr/bin/setsid" const val KILL = "/usr/bin/kill" + const val SH = "/bin/sh" val DEV_NULL = File("/dev/null") /** A child, a double-forked grandchild, the shell itself, and a child it waits for. */ diff --git a/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh b/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh index 56442ae56e..809f68befd 100644 --- a/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh +++ b/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh @@ -31,7 +31,8 @@ cd -- "${wd:-$HOME}" || exit 1 # A syntax error message quotes the command raw, so the syntax is checked first and an error is # shown with its control characters replaced. Exits 2, as eval does on a syntax error. The check # has extglob on: eval runs a command's lines one at a time, so a "shopt -s extglob" on one line -# applies to the next, but -n runs nothing. +# applies to the next, but -n runs nothing. The cost: an extglob pattern in a command that never +# turns extglob on passes the check, and eval's message rejecting it quotes the line raw. if ! err=$(bash -O extglob -n -c "$cmd" 2>&1); then while IFS= read -r line; do printf '%s\n' "${line//[[:cntrl:]]/?}"; done <<<"$err" >&2 exit 2 From 80286096fb2992fa2fdb54c6885387794feaaf3b Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 13:40:39 -0800 Subject: [PATCH 5/9] ADFA-7178: Reach children a command starts as an early stop lands A stop landing before the command has called setsid finds no group, so it killed only the held process. If setsid ran and the command started a child between that TERM and the kill, the child ran on. After killing the held process, such a stop now sends SIGKILL to the group once more. Raised by CodeRabbit's review of f1d9248ff. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../plugins/manager/services/ProcessGroups.kt | 6 ++- .../services/IdeCommandServiceImplTest.kt | 53 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt index 2f24d7cd3a..44b4efcb6d 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt @@ -53,10 +53,12 @@ internal class ProcessGroups( ) { val pgid = if (grouped) process.pidOrNull() else null if (grouped && pgid == null) log.warn("No process id for a command's group; stopping only its own process") + var noGroupYet = false if (pgid != null) { var left = signal(pgid, GroupSignal.TERM) // Expected only for a stop landing before setsid ran; otherwise setsid did not make a group. - if (!left && process.isAlive) log.warn("No process group {}; stopping only the command's own process", pgid) + noGroupYet = !left && process.isAlive + if (noGroupYet) log.warn("No process group {} yet; stopping the command's own process", pgid) val deadline = System.nanoTime() + KILL_AFTER_MS * NANOS_PER_MILLI while (left && System.nanoTime() < deadline) { delay(POLL_MS) @@ -66,6 +68,8 @@ internal class ProcessGroups( } // Also the whole story where there is no group. process.destroyForcibly() + // setsid may have run since the TERM found no group, and the command started children in it. + if (noGroupYet && pgid != null) signal(pgid, GroupSignal.KILL) } companion object { diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt index 40fb6d39ea..b1528c1a72 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt @@ -15,6 +15,8 @@ import org.junit.Assume.assumeTrue import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream import java.io.File import java.util.concurrent.CountDownLatch @@ -350,6 +352,22 @@ class IdeCommandServiceImplTest { assertThat((result as CommandResult.Success).stdout).isEqualTo("late\n") } + @Test + fun `a stop that finds no group yet signals the group again once the command is killed`() { + val sent = mutableListOf() + val process = FakeProcess { sent += "destroy" } + val groups = + ProcessGroups("/setsid") { pgid, signal -> + sent += "$signal $pgid" + // setsid runs, and the command starts a child, just after the TERM finds no group. + signal != GroupSignal.TERM + } + + runBlocking { groups.stop(process, grouped = true) } + + assertThat(sent).containsExactly("TERM ${FakeProcess.PID}", "destroy", "KILL ${FakeProcess.PID}").inOrder() + } + @Test fun `without setsid a timeout still stops the command itself`() { assumeHostTools() @@ -382,6 +400,41 @@ class IdeCommandServiceImplTest { assertThat(isolated).isEqualTo(GroupedCommand(command, grouped = false)) } + /** Alive until destroyed, with its process id where [ProcessGroups] reads it on Android. */ + private class FakeProcess( + private val onDestroy: () -> Unit, + ) : Process() { + @JvmField + val pid = PID + private var alive = true + + override fun getOutputStream() = ByteArrayOutputStream() + + override fun getInputStream() = ByteArrayInputStream(ByteArray(0)) + + override fun getErrorStream() = ByteArrayInputStream(ByteArray(0)) + + override fun waitFor() = 0 + + override fun exitValue() = if (alive) throw IllegalThreadStateException("running") else 0 + + override fun isAlive() = alive + + override fun destroy() { + alive = false + onDestroy() + } + + override fun destroyForcibly(): Process { + destroy() + return this + } + + companion object { + const val PID = 4242 + } + } + private companion object { const val SETSID = "/usr/bin/setsid" const val KILL = "/usr/bin/kill" From 83edad4242364bd6db450d1481f37c9c6c467ef7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 13:53:02 -0800 Subject: [PATCH 6/9] ADFA-7178: Use the Terminal's setsid where Android's forks Android 11's toybox setsid always forks, so there commands ran without a group of their own, and a stop left their children running. The IDE now also checks the util-linux setsid the Terminal installs, which runs in place whenever its caller leads no group, and uses the first of the two that runs commands in place. On the Note 20 (Android 13) the Terminal's setsid ran sh in place, as its own session and group leader, with an empty environment. There is no Android 11 device to check it on. Raised by CodeRabbit on f1d9248ff: ADFA-7178's acceptance criteria want no process a stopped command started left running. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- docs/PLUGIN_API_CHANGELOG.md | 5 +- .../manager/services/IdeCommandServiceImpl.kt | 2 +- .../plugins/manager/services/ProcessGroups.kt | 73 ++++++++++++------- .../services/IdeCommandServiceImplTest.kt | 35 ++++++--- 4 files changed, 76 insertions(+), 39 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index e65594e3bb..7ca52ff039 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -41,8 +41,9 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] process, never its children. Each command now runs in a process group of its own, and a timeout, `cancel()` or `cancelAllCommands()` stops the whole group: SIGTERM, then SIGKILL 250 ms later. `await()` returns within a second of the timeout, and a stopped command frees its slot. - On Android 11, whose `setsid` always forks, commands get no group of their own, and a stop - reaches only the command's own process, as before. + On Android 11, whose `setsid` always forks, the IDE uses the Terminal's `setsid` instead. If + the Terminal isn't installed when the IDE starts, commands there get no group of their own + until the next start, and a stop reaches only the command's own process, as before. A command that exits on its own is never reported as timed out. If a background child still holds its output 500 ms after the command exits, the child is stopped, and `await()` returns within about 1.5 s of the exit; a child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt index 19c902e734..a5ad0e1368 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt @@ -39,7 +39,7 @@ class IdeCommandServiceImpl internal constructor( private val projectRootProvider: () -> File?, private val appFilesDir: File, private val gradleTaskRunner: GradleTaskRunner = GradleTaskRunner(IdeBuildServiceImpl.getInstance()::startTasks), - private val processGroups: ProcessGroups = ProcessGroups.android, + private val processGroups: ProcessGroups = ProcessGroups.android(File(appFilesDir, "usr/bin/setsid")), ) : IdeCommandService { private val runningCommands = ConcurrentHashMap() diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt index 44b4efcb6d..0620c96d26 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt @@ -6,6 +6,7 @@ import android.system.OsConstants import kotlinx.coroutines.delay import org.slf4j.LoggerFactory import java.io.File +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit /** A signal [ProcessGroups] sends. [PROBE] delivers nothing; it only asks whether the group exists. */ @@ -83,40 +84,58 @@ internal class ProcessGroups( private const val ANDROID_SH = "/system/bin/sh" private const val CHECK_TIMEOUT_S = 5L - /** Android's toybox `setsid`, if it runs commands in place, and `kill(2)` through [Os]. */ - val android: ProcessGroups by lazy { - ProcessGroups(usableSetsid(ANDROID_SETSID, ANDROID_SH)) { pgid, signal -> - val number = - when (signal) { - GroupSignal.PROBE -> 0 - GroupSignal.TERM -> OsConstants.SIGTERM - GroupSignal.KILL -> OsConstants.SIGKILL - } - try { - Os.kill(-pgid, number) - true - } catch (e: ErrnoException) { - // ESRCH: the group is empty. - false + private val android = ConcurrentHashMap() + + /** + * Android's toybox `setsid`, or else [terminalSetsid], the util-linux one the Terminal installs, + * whichever first runs commands in place (see [usableSetsid]); and `kill(2)` through [Os]. + * Checked once per [terminalSetsid]. + */ + fun android(terminalSetsid: File): ProcessGroups = + android.computeIfAbsent(terminalSetsid.path) { + ProcessGroups(usableSetsid(listOf(ANDROID_SETSID, terminalSetsid.path), ANDROID_SH), ::osSignal) + } + + private fun osSignal( + pgid: Int, + signal: GroupSignal, + ): Boolean { + val number = + when (signal) { + GroupSignal.PROBE -> 0 + GroupSignal.TERM -> OsConstants.SIGTERM + GroupSignal.KILL -> OsConstants.SIGKILL } + return try { + Os.kill(-pgid, number) + true + } catch (e: ErrnoException) { + // ESRCH: the group is empty. + false } } /** - * [setsid] if it runs its command in place, which it checks by running [shell] under it once; - * otherwise null, with a warning. Toybox's `setsid` forks only when its caller leads a group, - * which a [ProcessBuilder] child never does, except in Android 11: there it makes itself a - * group leader first, so it always forks and exits 0 at once. Every command would then seem to - * end as it started, and its group would not be the one the IDE holds. + * The first of [candidates] that runs its command in place, which is checked by running [shell] + * under it once; null, with a warning, if none does. Toybox's `setsid`, like util-linux's, forks + * only when its caller leads a group, which a [ProcessBuilder] child never does, except in + * Android 11: there it makes itself a group leader first, so it always forks and exits 0 at + * once. Every command would then seem to end as it started, and its group would not be the one + * the IDE holds. */ fun usableSetsid( - setsid: String, + candidates: List, shell: String, ): String? { - if (!File(setsid).canExecute()) { - log.warn("No {}: a plugin's command can be stopped, but not the processes it starts", setsid) - return null - } + val setsid = candidates.firstOrNull { File(it).canExecute() && runsInPlace(it, shell) } + if (setsid == null) log.warn("No setsid runs commands in place: a stop reaches only a command's own process ({})", candidates) + return setsid + } + + private fun runsInPlace( + setsid: String, + shell: String, + ): Boolean { val inPlace = runCatching { val process = ProcessBuilder(setsid, shell, "-c", "echo \$\$").redirectErrorStream(true).start() @@ -127,8 +146,8 @@ internal class ProcessGroups( val printed = process.inputStream.bufferedReader().use { it.readLine() } printed != null && printed.trim() == process.pidOrNull()?.toString() }.getOrDefault(false) - if (!inPlace) log.warn("{} forks: a plugin's command can be stopped, but not the processes it starts", setsid) - return setsid.takeIf { inPlace } + if (!inPlace) log.warn("{} forks, so it is not used", setsid) + return inPlace } } } diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt index b1528c1a72..d773c5905c 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt @@ -73,7 +73,7 @@ class IdeCommandServiceImplTest { resultFor(CommandSpec.ShellCommand("true", workingDirectory = workingDirectory)) private fun resultFor(spec: CommandSpec): CommandResult { - val execution = service(ProcessGroups.android).executeCommand(spec, 5_000) + val execution = service(ProcessGroups.android(File(filesDir, "usr/bin/setsid"))).executeCommand(spec, 5_000) return runBlocking { execution.await() } } @@ -328,30 +328,47 @@ class IdeCommandServiceImplTest { fun `setsid is used when it runs the command in place`() { assumeHostTools() - assertThat(ProcessGroups.usableSetsid(SETSID, SH)).isEqualTo(SETSID) + assertThat(ProcessGroups.usableSetsid(listOf(SETSID), SH)).isEqualTo(SETSID) } @Test fun `a missing setsid is not used`() { - assertThat(ProcessGroups.usableSetsid(File(tmp.root, "none").path, SH)).isNull() + assertThat(ProcessGroups.usableSetsid(listOf(File(tmp.root, "none").path), SH)).isNull() } // As Android 11's toybox setsid does: it forks, and its parent exits 0 at once. @Test fun `a setsid that forks is not used, so a command still runs to its end`() { assumeHostTools() - val forking = - File(tmp.root, "setsid").apply { - writeText("#!/bin/sh\n\"\$@\" &\nexit 0\n") - setExecutable(true) - } - val groups = ProcessGroups(ProcessGroups.usableSetsid(forking.path, SH), ::hostSignal) + val groups = ProcessGroups(ProcessGroups.usableSetsid(listOf(forkingSetsid().path), SH), ::hostSignal) val result = service(groups).executeCommand(shell("sleep 1; echo late"), 10_000).awaitWithin(10_000) assertThat((result as CommandResult.Success).stdout).isEqualTo("late\n") } + // Android 11 again, with the Terminal's util-linux setsid installed: commands still get a group. + @Test + fun `where the first setsid forks, the next one that runs commands in place is used`() { + assumeHostTools() + val setsid = ProcessGroups.usableSetsid(listOf(forkingSetsid().path, File(tmp.root, "none").path, SETSID), SH) + val groups = ProcessGroups(setsid, ::hostSignal) + + val execution = service(groups).executeCommand(shell(CHILDREN_SCRIPT), 300) + val result = execution.awaitWithin(10_000) + + assertThat(setsid).isEqualTo(SETSID) + assertThat((result as CommandResult.Failure).error).isEqualTo("Command timed out after 300ms") + assertThat(goneWithin(pids(CHILDREN_SCRIPT_PIDS), 1_000)).isTrue() + } + + /** A `setsid` that forks and exits 0 at once, as Android 11's toybox one does. */ + private fun forkingSetsid() = + File(tmp.root, "forking-setsid").apply { + writeText("#!/bin/sh\n\"\$@\" &\nexit 0\n") + setExecutable(true) + } + @Test fun `a stop that finds no group yet signals the group again once the command is killed`() { val sent = mutableListOf() From 472652f17a4afbbb5f4e10af1c31effaee032e21 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 14:10:14 -0800 Subject: [PATCH 7/9] ADFA-7178: Say when the Terminal's setsid is used The changelog now says the Terminal's setsid is used only if it passes the IDE's check, and that where neither setsid does, a stop leaves a command's children running. Raised by CodeRabbit's review of 83edad424. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- docs/PLUGIN_API_CHANGELOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 7ca52ff039..ae02f1f38e 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -41,9 +41,10 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] process, never its children. Each command now runs in a process group of its own, and a timeout, `cancel()` or `cancelAllCommands()` stops the whole group: SIGTERM, then SIGKILL 250 ms later. `await()` returns within a second of the timeout, and a stopped command frees its slot. - On Android 11, whose `setsid` always forks, the IDE uses the Terminal's `setsid` instead. If - the Terminal isn't installed when the IDE starts, commands there get no group of their own - until the next start, and a stop reaches only the command's own process, as before. + On Android 11, whose `setsid` always forks, the IDE uses the Terminal's `setsid` instead, but + only if that one runs commands in place when the IDE first checks it. Where neither does, for + example because the Terminal isn't installed yet, commands get no group of their own until the + IDE's next start, and a stop leaves their children running, as before. A command that exits on its own is never reported as timed out. If a background child still holds its output 500 ms after the command exits, the child is stopped, and `await()` returns within about 1.5 s of the exit; a child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process From e4e9e7d8c91741d26dba4c0b4c400595f146b669 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 14:46:32 -0800 Subject: [PATCH 8/9] ADFA-7178: Pin the cancel paths' reader threads and the grace timing From an independent review of the whole PR at 472652f17: - The cancel and cancelAllCommands() tests now check that no output reader is left, as the timeout test does. - The grace test checks the changelog's promise, about 1.5 s after the exit, as a fixed bound. Before, the bound grew with the grace constant. - The slot test's three commands time out after 1 s, not 300 ms, so none has timed out by the fourth call on a slow machine. - agent-run.sh's comment says the syntax check runs none of a broken command, where eval runs the lines ahead of the error. Run alone on a cold JVM, the grace test failed: the shell exited before the reader was in read(), so Process drained and closed the output (ProcessPipeInputStream.processExited), and the child holding it went unseen. Android's UNIXProcess does the same. The two tests that rely on such a child now let the readers start before the shell exits, and the code comment and changelog name the race. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- docs/PLUGIN_API_CHANGELOG.md | 4 ++- .../manager/services/IdeCommandServiceImpl.kt | 4 ++- .../services/IdeCommandServiceImplTest.kt | 34 ++++++++++++++++--- .../itsaky/androidide/terminal/agent-run.sh | 9 ++--- 4 files changed, 40 insertions(+), 11 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index ae02f1f38e..82f8b019ef 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -47,7 +47,9 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] IDE's next start, and a stop leaves their children running, as before. A command that exits on its own is never reported as timed out. If a background child still holds its output 500 ms after the command exits, the child is stopped, and `await()` returns - within about 1.5 s of the exit; a child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process + within about 1.5 s of the exit. A command that exits before the IDE starts reading its output + is the exception: Java drains and closes the output as it exits, so such a child is not seen. + A child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process that calls `setsid` itself. - **breaking — JavaScript highlighting and the IDE's grammar names are the IDE's** _(ADFA-7084)_ The IDE now highlights `js`, `mjs`, `cjs` and `jsx` itself. A `LanguageDefinition` can still diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt index a5ad0e1368..e12df3bdd6 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt @@ -203,7 +203,9 @@ internal class CommandExecutionImpl( exitCode = started?.takeUnless { it.isAlive }?.exitValue() if (exitCode != null) { // Not under the timeout: the command has ended. A background child can hold the - // output open long after that, and is then stopped below. + // output open long after that, and is then stopped below. Unless no reader was in + // read() yet when the command exited: Process then drains the pipe and closes its + // end (ProcessPipeInputStream.processExited), so the output looks closed. outputClosed = withTimeoutOrNull(outputGraceMs) { readers.joinAll() } != null } } catch (e: CancellationException) { diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt index d773c5905c..a9ca583e7a 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt @@ -112,6 +112,16 @@ class IdeCommandServiceImplTest { return true } + /** Whether every command's output reader has ended within [ms]. A cancel returns before they do. */ + private fun readersGoneWithin(ms: Long): Boolean { + val deadline = System.currentTimeMillis() + ms + while (readerThreads().isNotEmpty()) { + if (System.currentTimeMillis() > deadline) return false + Thread.sleep(10) + } + return true + } + /** Threads still in a command's output reader. */ private fun readerThreads(): List { val reader = "${CommandExecutionImpl::class.java.name}\$readLines" @@ -175,6 +185,7 @@ class IdeCommandServiceImplTest { execution.cancel() assertThat(execution.awaitWithin(1_000)).isInstanceOf(CommandResult.Cancelled::class.java) + assertThat(readersGoneWithin(1_000)).isTrue() assertThat(goneWithin(pids, 1_000)).isTrue() } @@ -215,6 +226,7 @@ class IdeCommandServiceImplTest { service.cancelAllCommands() + assertThat(readersGoneWithin(1_000)).isTrue() assertThat(goneWithin(pids, 1_000)).isTrue() assertThat(service.getRunningCommandCount()).isEqualTo(0) } @@ -222,7 +234,7 @@ class IdeCommandServiceImplTest { @Test fun `a command that exits before its timeout is not timed out while a child holds its output`() { assumeHostTools() - val script = "echo done; sleep 600 & echo \$! >> \"\$1\"" + val script = "echo done; sleep 600 & echo \$! >> \"\$1\"; $LET_READERS_START" // The output stays open past the 1 s limit, until the grace ends and the child is stopped. val execution = CommandExecutionImpl( @@ -262,9 +274,12 @@ class IdeCommandServiceImplTest { assumeHostTools() val started = System.currentTimeMillis() - val result = service().executeCommand(shell("echo done; sleep 600 & echo \$! >> \"\$1\""), 60_000).awaitWithin(10_000) + val script = "echo done; sleep 600 & echo \$! >> \"\$1\"; $LET_READERS_START" - assertThat(System.currentTimeMillis() - started).isLessThan(CommandExecutionImpl.OUTPUT_GRACE_MS + 1_000) + val result = service().executeCommand(shell(script), 60_000).awaitWithin(10_000) + + // What the changelog promises: within about 1.5 s of the exit. + assertThat(System.currentTimeMillis() - started).isLessThan(LET_READERS_START_MS + 1_500) assertThat(result).isInstanceOf(CommandResult.Success::class.java) assertThat((result as CommandResult.Success).stdout).isEqualTo("done\n") assertThat(readerThreads()).isEmpty() @@ -285,8 +300,9 @@ class IdeCommandServiceImplTest { fun `stopped commands free their slots`() { assumeHostTools() val service = service() - val timedOut = List(3) { service.executeCommand(shell("sleep 600"), 300) } - assertThrows(IllegalStateException::class.java) { service.executeCommand(shell("true"), 300) } + // Long enough that none has timed out by the fourth call, even on a slow machine. + val timedOut = List(3) { service.executeCommand(shell("sleep 600"), 1_000) } + assertThrows(IllegalStateException::class.java) { service.executeCommand(shell("true"), 1_000) } timedOut.forEach { it.awaitWithin(10_000) } val deadline = System.currentTimeMillis() + 1_000 @@ -456,6 +472,14 @@ class IdeCommandServiceImplTest { const val SETSID = "/usr/bin/setsid" const val KILL = "/usr/bin/kill" const val SH = "/bin/sh" + + /** + * Ends a script that leaves a child holding its output, so that the readers are in read() + * before the shell exits. A shell that exits first has its output drained and closed by + * [Process], which hides the child. + */ + const val LET_READERS_START_MS = 200L + const val LET_READERS_START = "sleep 0.2" val DEV_NULL = File("/dev/null") /** A child, a double-forked grandchild, the shell itself, and a child it waits for. */ diff --git a/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh b/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh index 809f68befd..dfdf9d24b1 100644 --- a/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh +++ b/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh @@ -29,10 +29,11 @@ mark C printf '$ %s\n' "$shown" cd -- "${wd:-$HOME}" || exit 1 # A syntax error message quotes the command raw, so the syntax is checked first and an error is -# shown with its control characters replaced. Exits 2, as eval does on a syntax error. The check -# has extglob on: eval runs a command's lines one at a time, so a "shopt -s extglob" on one line -# applies to the next, but -n runs nothing. The cost: an extglob pattern in a command that never -# turns extglob on passes the check, and eval's message rejecting it quotes the line raw. +# shown with its control characters replaced. Exits 2, as eval does on a syntax error, but before +# any of the command runs: eval would run the lines ahead of the error. The check has extglob on: +# eval runs a command's lines one at a time, so a "shopt -s extglob" on one line applies to the +# next, but -n runs nothing. The cost: an extglob pattern in a command that never turns extglob on +# passes the check, and eval's message rejecting it quotes the line raw. if ! err=$(bash -O extglob -n -c "$cmd" 2>&1); then while IFS= read -r line; do printf '%s\n' "${line//[[:cntrl:]]/?}"; done <<<"$err" >&2 exit 2 From 7647dfb75e6db82df9d8f8d0f5c29b3008b0c7d3 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 15:13:55 -0800 Subject: [PATCH 9/9] ADFA-7178: Release the child-holding tests' shells once the readers read The two tests that leave a child holding a command's output let the readers start with a fixed 0.2 s sleep before the shell exits. A host that starts the readers later would have had the output drained and closed at the exit, the child hidden, and the tests failing. The shell now waits for a release file, which the test creates once `done` has been read and both readers are blocked in read() again. Run alone on a fresh JVM, the grace test failed 5 of 5 times when released at once, and passed 5 of 5 with the handshake. The grace test measures from the release, and the timeout test's limit and grace go from 1 s and 2 s to 2 s and 3 s, so that the shell is released well before its timeout. A shell whose test fails before the release ends when the test's folder is deleted. Raised by CodeRabbit's review of e4e9e7d8c. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../services/IdeCommandServiceImplTest.kt | 75 +++++++++++++------ 1 file changed, 53 insertions(+), 22 deletions(-) diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt index a9ca583e7a..b3eec8c186 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt @@ -2,10 +2,12 @@ package com.itsaky.androidide.plugins.manager.services import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.plugins.PluginPermission +import com.itsaky.androidide.plugins.extensions.CommandOutput import com.itsaky.androidide.plugins.extensions.CommandResult import com.itsaky.androidide.plugins.extensions.CommandSpec import com.itsaky.androidide.plugins.services.CommandExecution import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout @@ -18,6 +20,7 @@ import org.junit.rules.TemporaryFolder import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.File +import java.io.FileInputStream import java.util.concurrent.CountDownLatch class IdeCommandServiceImplTest { @@ -28,6 +31,9 @@ class IdeCommandServiceImplTest { private val filesDir by lazy { tmp.newFolder("files") } private val pidFile by lazy { File(tmp.root, "pids") } + /** Created by [releaseOnceReading] to end a script's [WAIT_FOR_RELEASE]. */ + private val releaseFile by lazy { File(tmp.root, "release") } + /** `setsid` and `kill` from util-linux and procps, standing in for Android's toybox and [android.system.Os]. */ private val hostGroups = ProcessGroups(SETSID, ::hostSignal) @@ -77,8 +83,25 @@ class IdeCommandServiceImplTest { return runBlocking { execution.await() } } - /** `sh -c [script]`, where `$1` is [pidFile] for the script to write the ids of its processes to. */ - private fun shell(script: String) = CommandSpec.ShellCommand("sh", listOf("-c", script, "sh", pidFile.path)) + /** + * `sh -c [script]`, where `$1` is [pidFile] for the script to write the ids of its processes to, + * and `$2` is [releaseFile]. + */ + private fun shell(script: String) = CommandSpec.ShellCommand("sh", listOf("-c", script, "sh", pidFile.path, releaseFile.path)) + + /** + * Lets a script that echoed `done` and ends in [WAIT_FOR_RELEASE] exit, once `done` has been read + * and both output readers are blocked in read() again, where they hold the output open. + */ + private fun CommandExecution.releaseOnceReading() { + runBlocking { withTimeout(5_000) { output.first { it == CommandOutput.StdOut("done") } } } + val deadline = System.currentTimeMillis() + 5_000 + while (Thread.getAllStackTraces().values.count { it.inReader() && it.inRead() } < 2) { + check(System.currentTimeMillis() < deadline) { "the output readers are not in read()" } + Thread.sleep(5) + } + releaseFile.createNewFile() + } private fun CommandExecution.awaitWithin(ms: Long): CommandResult = runBlocking { withTimeout(ms) { await() } } @@ -123,15 +146,21 @@ class IdeCommandServiceImplTest { } /** Threads still in a command's output reader. */ - private fun readerThreads(): List { - val reader = "${CommandExecutionImpl::class.java.name}\$readLines" - return Thread + private fun readerThreads(): List = + Thread .getAllStackTraces() - .filterValues { frames -> frames.any { it.className.startsWith(reader) } } + .filterValues { it.inReader() } .keys .map { it.name } + + private fun Array.inReader(): Boolean { + val reader = "${CommandExecutionImpl::class.java.name}\$readLines" + return any { it.className.startsWith(reader) } } + /** Blocked reading a pipe, inside the process stream's lock that its exit has to take to close it. */ + private fun Array.inRead(): Boolean = any { it.className == FileInputStream::class.java.name } + private fun assumeHostTools() = assumeTrue( "needs util-linux setsid and procps kill", @@ -234,18 +263,19 @@ class IdeCommandServiceImplTest { @Test fun `a command that exits before its timeout is not timed out while a child holds its output`() { assumeHostTools() - val script = "echo done; sleep 600 & echo \$! >> \"\$1\"; $LET_READERS_START" - // The output stays open past the 1 s limit, until the grace ends and the child is stopped. + val script = "echo done; sleep 600 & echo \$! >> \"\$1\"; $WAIT_FOR_RELEASE" + // The output stays open past the 2 s limit, until the grace ends and the child is stopped. val execution = CommandExecutionImpl( "test", - ProcessBuilder(SETSID, "sh", "-c", script, "sh", pidFile.path)::start, + ProcessBuilder(SETSID, "sh", "-c", script, "sh", pidFile.path, releaseFile.path)::start, grouped = true, processGroups = hostGroups, - timeoutMs = 1_000, - outputGraceMs = 2_000, + timeoutMs = 2_000, + outputGraceMs = 3_000, ) execution.start {} + execution.releaseOnceReading() val result = execution.awaitWithin(10_000) @@ -253,7 +283,7 @@ class IdeCommandServiceImplTest { result as CommandResult.Success assertThat(result.stdout).isEqualTo("done\n") assertThat(result.stderr).isEmpty() - assertThat(result.durationMs).isAtLeast(2_000) + assertThat(result.durationMs).isAtLeast(3_000) assertThat(pids(1).filter(::alive)).isEmpty() } @@ -272,14 +302,14 @@ class IdeCommandServiceImplTest { @Test fun `a command returns soon after it exits though a child holds its output`() { assumeHostTools() - val started = System.currentTimeMillis() + val execution = service().executeCommand(shell("echo done; sleep 600 & echo \$! >> \"\$1\"; $WAIT_FOR_RELEASE"), 60_000) + execution.releaseOnceReading() + val released = System.currentTimeMillis() - val script = "echo done; sleep 600 & echo \$! >> \"\$1\"; $LET_READERS_START" - - val result = service().executeCommand(shell(script), 60_000).awaitWithin(10_000) + val result = execution.awaitWithin(10_000) // What the changelog promises: within about 1.5 s of the exit. - assertThat(System.currentTimeMillis() - started).isLessThan(LET_READERS_START_MS + 1_500) + assertThat(System.currentTimeMillis() - released).isLessThan(1_500) assertThat(result).isInstanceOf(CommandResult.Success::class.java) assertThat((result as CommandResult.Success).stdout).isEqualTo("done\n") assertThat(readerThreads()).isEmpty() @@ -474,12 +504,13 @@ class IdeCommandServiceImplTest { const val SH = "/bin/sh" /** - * Ends a script that leaves a child holding its output, so that the readers are in read() - * before the shell exits. A shell that exits first has its output drained and closed by - * [Process], which hides the child. + * Ends a script that leaves a child holding its output: the shell waits for `$2` to exist, + * which [releaseOnceReading] creates once the readers are in read(). A shell that exits first + * has its output drained and closed by [Process], which hides the child. Also ends once `$1`, + * which the script has written to, is deleted with the test's folder, so that a test failing + * first leaves no shell behind. */ - const val LET_READERS_START_MS = 200L - const val LET_READERS_START = "sleep 0.2" + const val WAIT_FOR_RELEASE = "until [ -e \"\$2\" ] || [ ! -e \"\$1\" ]; do sleep 0.01; done" val DEV_NULL = File("/dev/null") /** A child, a double-forked grandchild, the shell itself, and a child it waits for. */