如何在ctrl + c之后终止Gradle构建中的shell进程

时间:2018-01-05 16:09:12

标签: shell gradle groovy

如果使用ctrl-c终止Gradle构建时,如何在cmd.execute() - 调用中创建进程。

在此示例中,calcTask-task启动shell进程'longRunningProcess.bat',即'sleep 300'。当使用ctrl + c中止Gradle构建时,“睡眠”过程仍处于活动状态。异常会处理shell中的错误但不会处理ctrl + c。

apply plugin: "groovy"

dependencies {
  compile gradleApi()
}

task CreateLongRunningProcess(type: DefaultTask) {
    def file = new File('longRunningProcess.bat')
    file.write '@ECHO Start calculating - please wait 5 minutes.\n'
    file << '@sleep 300\n'
    file << '@ECHO Finished calculating.\n'
}

class CalcTask extends DefaultTask {
    @TaskAction
    def calculate() {
        String cmd = './longRunningProcess.bat'
        try {
            def proc = cmd.execute()
            proc.waitForProcessOutput(System.out, System.err)
        } catch (Exception e) {
            e.printStackTrace();
            println 'Exception occured'
        }
    }
}

task calcTask(type: CalcTask) {
    dependsOn(CreateLongRunningProcess)
}
$ ps -ef | grep sleep
$ ./gradlew -q calcTask
Start calculating - please wait 5 minutes.

<Aborted with ctrl+c>
$ ps -ef | grep sleep
 t035678    1900       1 ?        16:55:58 /usr/bin/sleep
$ kill 1900
$ ./longRunningProcess.bat
Start calculating - please wait 5 minutes.
<Aborted with ctrl+c>
Finished calculating.
$ ps -ef | grep sleep
$ ./gradlew --version
<snip>

------------------------------------------------------------
Gradle 4.4
------------------------------------------------------------

Build time:   2017-12-06 09:05:06 UTC
Revision:     cf7821a6f79f8e2a598df21780e3ff7ce8db2b82

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM:          9.0.1 (Oracle Corporation 9.0.1+11)
OS:           Windows 7 6.1 amd64

0 个答案:

没有答案