pax
pax

Reputation: 90

How do I send output of two commands' output to standard out in parallel?

I want to use xinput to monitor # of keystrokes and # of mouse movement presses. For simplification let's say what I want is these two commands:

xinput test 0
xinput test 1

to write to the screen at the same time.

I am using this in a Perl script like:

open(my $fh, '-|', 'xinput test 0') or die $!;
while(my $line = <$fh>) {
...stuff to keep count instead of logging directly to file
}

EDIT: something like:

open(my $fh, '-|', 'xinput test 0 & xinput test 1') or die $!;

doesn't work.

Upvotes: 2

Views: 109

Answers (2)

brian d foy
brian d foy

Reputation: 132905

I'm not sure what you want to do with the output, but it sounds like you want to run the commands simultaneously. In that case, my first thought would be to fork the Perl process once per command and then exec the child processes to the commands you care about.

foreach my $command ( @commands ) {  # filter @commands for taint, etc
    if( fork ) { ... } #parent
    else { # child
        exec $command or die "Could not exec [$command]! $!";
        }
    }

The forked processes share the same standard filehandles. If you need their data in the parent process, you'd have to set up some sort of communication between the two.

There are also several Perl frameworks on CPAN for handling asynchronous multi-process stuff, such as POE, AnyEvent, and so on. They'd handle all these details for you.

Upvotes: 2

Tomas
Tomas

Reputation: 59575

If you want to write both command on the console simultaneously, simply run them on the background:

xinput test 0 &
xinput test 1 &

But first you have to make sure that the console is set into the regime which allows that, otherwise the background processes will get stopped when trying to write on console. This code will switch off the stty tostop option:

stty -tostop

Upvotes: 0

Related Questions