Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Keystroke to different process using Bash

I have a process that runs indefinitely until a key is pressed. I would like to use bash to inject a keystroke into this process to have it terminate. Based on this post, linux - write commands from one terminal to another I have tried to use

echo -e "b" > /proc/[pid]/fd/0

(The letter "b" in this case is just arbitrary) The letter "b" will show up in the terminal of the process that is running indefinitely, but it doesn't trigger the termination of the program like it does if I actually type "b" into the window.

I have also seen the recommendation for xdotools, but I couldn't get it to work and am trying to stay away from relying on GUI for implementing this.

I am running Ubuntu 10.04, and I don't have much experience in bash.

like image 990
Max Avatar asked Mar 27 '26 02:03

Max


1 Answers

From here:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>

int main(void)
    {
    int hTTY = open("/dev/tty1", O_WRONLY|O_NONBLOCK);
    ioctl(hTTY, TIOCSTI, "b");

    close(hTTY);
    return 0;
    }

The terminal and keystroke are hardcoded in this example, but it can be adapted to your needs.

You can do something similar in Perl:

perl -e '$TIOCSTI = 0x5412; $tty = "/dev/pts/1"; $char = "b"; open($fh, ">", $tty); ioctl($fh, $TIOCSTI, $char)'

I have to run either of these with sudo.

like image 123
Dennis Williamson Avatar answered Mar 29 '26 21:03

Dennis Williamson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!