【问题标题】:How to get passthru to draw progress bars (e.g. w/ scp)?如何获得通过来绘制进度条(例如 w/scp)?
【发布时间】:2015-08-04 18:47:12
【问题描述】:

我正在使用passthru 运行scp。通常 scp 会输出一个进度条,但是当我使用passthru 时它不会被绘制。我想估计一下转移需要多长时间。有没有办法强制它显示?

【问题讨论】:

标签: php bash scp


【解决方案1】:

大多数与 libc 链接的程序使用函数isatty 在决定对其输出进行着色之前检查 stdout 是否是终端。因此,要确保 ANSI 终端转义序列不会搞砸管道或重定向到文件中。 passthru() 不会在终端中运行命令。

在 PHP 中,您可以使用 proc_open() 打开一个进程并将其显示为标准输出的终端。以手册中的这个例子为例,我已经修改为使用pty 而不是pipe 用于stdoutstderr

$descriptorspec = array(
   0 => array("pipe", "r"), // stdin is a pipe that the child will read from
   1 => array("pty", "w"),  // stdout is a pty that the child will write to
   2 => array("pty", "w")   // stderr is a pty that the child will write to
);

$cwd = '/tmp';
$env = array('some_option' => 'aeiou');

$process = proc_open('command', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], '<?php print_r($_ENV); ?>');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);
    echo stream_get_contents($pipes[2]);
    fclose($pipes[2]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}

但是,您也可以在启动进程时使用LD_PRELOAD,并以它认为 stdout 是终端的方式欺骗​​程序。 (骇人听闻,但有时是最后的手段)。我在这里描述过:Bash: trick program into thinking stdout is an interactive terminal

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 2013-08-06
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    相关资源
    最近更新 更多