Groovy管道是真正的UNIX管道吗?

Chr*_*her 10 groovy

我今天刚开始研究Groovy.我考虑用它来替换一些更复杂的bash脚本.

对我来说,其中一个非常有趣的概念是可以轻松使用管道:

proc1 = 'ls'.execute()
proc2 = 'tr -d o'.execute()
proc3 = 'tr -d e'.execute()
proc4 = 'tr -d i'.execute()
proc1 | proc2 | proc3 | proc4
proc4.waitFor()
Run Code Online (Sandbox Code Playgroud)

棒极了.但我的问题是:这是否使用真正的UNIX管道(例如在Linux上运行时),或者这只是一个使用Java流的模拟?(如果是这样,它会慢得多/效率低吗?)

小智 6

由于运算符重载,它最终调用Groovy运行时的ProcessGroovyMethods.pipeTo(),它确实使用java流模拟管道:

    /**
     * Allows one Process to asynchronously pipe data to another Process.
     *
     * @param left  a Process instance
     * @param right a Process to pipe output to
     * @return the second Process to allow chaining
     * @throws java.io.IOException if an IOException occurs.
     * @since 1.5.2
     */
    public static Process pipeTo(final Process left, final Process right) throws IOException {
        new Thread(new Runnable() {
            public void run() {
                InputStream in = new BufferedInputStream(getIn(left));
                OutputStream out = new BufferedOutputStream(getOut(right));
                byte[] buf = new byte[8192];
                int next;
                try {
                    while ((next = in.read(buf)) != -1) {
                        out.write(buf, 0, next);
                    }
                } catch (IOException e) {
                    throw new GroovyRuntimeException("exception while reading process stream", e);
                } finally {
                    closeWithWarning(out);
                }
            }
        }).start();
        return right;
    }
Run Code Online (Sandbox Code Playgroud)

我无法谈论我头顶的开销量.


小智 5

我发现groovy管道模拟比unix管道慢得多:

Bash命令

zcat dump.sql.gz | mysql -u${mysql_user} --password=${mysql_password} -D${db_name} 
Run Code Online (Sandbox Code Playgroud)

大约需要40分钟

与groovy相同的事情

def proc1 = ["zcat", "${sqlGzFile.getPath()}"].execute()
def proc2 = ["mysql", "-u${mysqlUser}", "--password=${mysqlPassword}", "-D$dbName"].execute()   
proc1 | proc2
proc2.waitFor()
Run Code Online (Sandbox Code Playgroud)

大约需要2小时40分钟

但你可以做管道:

def proc = ["sh", "-c",  "zcat dump.sql.gz | mysql -u${mysql_user} --password=${mysql_password} -D${db_name}"].execute()
proc.waitFor()
Run Code Online (Sandbox Code Playgroud)