简体   繁体   中英

How to print output to two different terminals in php?

I am running two for loops in parallel using amphp/parallel-functions. I am wondering how can I see the live output printing parallelly? I am thinking of printing to two different terminals. Can it be possible? If no how can I track the output if it is running parallelly or sequentially?

<?php
require "vendor/autoload.php";

use Amp\Promise;
use Amp\ParallelFunctions;

$promises[1] = ParallelFunctions\parallel(function (){

    for ($i=0; $i<50; $i++){
        echo 'Promise-1 : '. $i . PHP_EOL;
    }

})();

$promises[2] = ParallelFunctions\parallel(function (){

    for ($i=0; $i<50; $i++){
        echo 'Promise-2 : '. $i .PHP_EOL;
    }

})();

Promise\wait(Promise\all($promises));

Current Output seems to be sequential

Promise-1 : 0
Promise-1 : 1
Promise-1 : 2
Promise-1 : 3
Promise-1 : 4
Promise-2 : 0
Promise-2 : 1
Promise-2 : 2
Promise-2 : 3
Promise-2 : 4

Note I am using a mac and this is purely to test on my local.

Disclaimer : Printing to a terminal is going to be inherently very dependent on the OS and not really a very stable system: What do you do when the user closes the terminal? What happens if you have something else already running on the first terminal?

With that out of the way here is how you can do it:

On most versions of linux you can write to the virtual files found at /dev/pts/ (for example /dev/pts/1) to output on any open terminal. You can try it out by opening two terminal instances and typing the following in the second one:

echo "testing" > /dev/pts/0

This should print testing on the first terminal. However it won't work on mac, since there is no /dev/pts folder, however you can instead type the following in the second terminal:

echo "testing" > /dev/ttys000

or in php:

$fp = fopen('dev/ttys000');
fwrite($fp, "testing\n");
fclose($fp);

If it is possible at all on Windows, it's almost certainly much more complicated than writing to a file.

In general I recommend writing the output to separate log files in this sort of situation instead of the terminal

amphp/parallel uses child processes to run these in parallel. STDOUT and STDERR of the child processes are piped into the parent's STDOUT and STDERR respectively. As streams are read and written in chunks, the output order does likely not represent the actual execution order.

If you put sleep calls into the for loops, you'll likely be able to observe the interleaved execution order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM