Skip to content

Proper streams closure after running cmd in JavaScript #1591

Description

@rudolf101

Description

Figure out how to properly close input and error stream after running cmd.
Currently, the closure of the streams is not controlled, which can lead to a loss of resources.

To Reproduce

  1. Open utbot-js/../utils/JsCmdExec.kt
  2. Go to usages of runCommand function
  3. Look at the operations with the returned bufferReader

Expected behavior

After executing the cmd command, the inputStream and errorStream text should be obtained, both streams should be closed properly.

Actual behavior

The closure of streams is not controlled properly.

Potential problem solution

Close the streams in runCommand function and return a Pair<String, String>

fun runCommand(
        dir: String? = null,
        shouldWait: Boolean = false,
        timeout: Long = defaultTimeout,
        vararg cmd: String,
    ): Pair<String, String> {
        val builder = ProcessBuilder(*OsProvider.getProviderByOs().getCmdPrefix(), *cmd)
        dir?.let {
            builder.directory(File(it))
        }
        val process = builder.start()
        if (shouldWait) {
            if (!process.waitFor(timeout, TimeUnit.SECONDS)) {
                process.descendants().forEach {
                    it.destroy()
                }
                process.destroy()
                throw TimeoutException("")
            }
        }
        return Pair(
            process.inputStream.bufferedReader().use { it.readText() },
            process.errorStream.bufferedReader().use { it.readText() }
        )
    }

Metadata

Metadata

Assignees

Labels

ctg-bugIssue is a buglang-javascriptIssue is related to JavaScript support

Type

No type
No fields configured for issues without a type.

Projects

Status
Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions