在终端上运行时,ProcessBuilder代码的行为有所不同

时间:2019-11-24 15:06:30

标签: java kotlin processbuilder kotlin-coroutines

当我在IDE(IntelliJ IDEA)中运行以下代码时,该过程将按预期成功执行。但是,当涉及到在终端(Mac OS)上运行该程序时,该程序会卡在内部触发进程的提示上,该进程应该由我的InputStream处理捕获,但没有发生。.知道为什么这正在发生,如何解决呢?由于我的问题与ProcessBuilderInputStream处理有关,因此我省略了与该上下文无关的代码(static main方法等)

终端命令和输出:(注意:sslTool.jar只是我的程序,其中包含下面提供的代码。执行带有给定参数的程序会使该程序调用我的代码的功能。但是问题是第二行不应由我的程序输出,而应在内部处理)

java -jar sslTool.jar pem-to-jks -in "../../../dummy/bundle.crt" -inKey "../../../dummy/priv.key" -destkeystore sslCert.jks -deststorepass 123 -destkeypass 123456 -destalias sslCert
Enter Export Password:

代码:

fun convertPemToPkcs12(bundleCrt: File, privKey: File, pkcs12Pw: String, pkcs12Name: String = "alias"): File? {

    val pkcs12 = PROCESSING_FOLDER.resolve("keystore.pkcs12")
    pkcs12.delete()

    val process = ProcessBuilder().directory(PROCESSING_FOLDER)
        .command(
                "openssl", "pkcs12" ,"-export",
                "-in", bundleCrt.absolutePath,
                "-inkey", privKey.absolutePath,
                "-out", pkcs12.absolutePath, "-name", pkcs12Name
        )
        .redirectErrorStream(true)
        .start()

    val pkcs12File = runBlocking {
        process.inputStream.bufferedReader().use { reader ->
            while(true) {
                println("read")
                if(reader.ready()) {
                    val prompt = reader.readCurrent().trim('\n')
                    if(prompt == "Enter Export Password:" || prompt == "Verifying - Enter Export Password:") {
                        process.typeIn(pkcs12Pw)
                    } else {

                        val result = if(prompt.isNotBlank()) {
                            err.println("unexpected prompt: $prompt")
                            null
                        } else pkcs12

                        return@runBlocking result
                    }
                }
            }
            @Suppress("UNREACHABLE_CODE")
            return@runBlocking null
        }
    }

    process.waitFor()

    return pkcs12File
}

private fun BufferedReader.readCurrent(): String {
    val buf = CharArray(4096)
    return buildString {
        while (true) {
            val size = read(buf)
            if(size <= 0) break
            else {
                append(buf, 0, size)
                if(size < 4096) break
            }
        }
    }
}

0 个答案:

没有答案