Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send keyboard input to a running process linux

I am developing web interface for an mp3 player (mpg123 linux). The mpg123 is a command-line mp3 player and can be controlled using keyboard inputs. For example:

$ mpg123 -C filename.mp3

it will start playing the song and monitor keyboard inputs for control. Pressing 's' will pause the song 'q' for quit etc.

I am spawning an mpg123 process using a Perl script. From that script I want to send inputs to this process. I have the pid of the process, I just need to send keystrokes to this process for control purpose.

like image 414
Punit Soni Avatar asked Oct 10 '10 19:10

Punit Soni


1 Answers

You just have to spawn your mp3-player as a pipe from perl. Like so:

$| = 1; # Set unbuffered output.
open( my $mp3player, "| mpg123" ) or die "cannot start mp3 player: $!";
print $mp3player "s";
...
print $mp3player "q";
close $mp3player

Second try for multiple script invocations: In an interactive shell enter tty. That will give you a pseudo-terminal name. Now start your player in this shell. In another shell, write to that pseudo-terminal. E.g. echo "s" > /dev/pts/11. The player will receive this as input. If this works, use your perl script instead of echo to write to the pseudo-terminal.

like image 125
Peter G. Avatar answered Oct 04 '22 20:10

Peter G.