3

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.

Community
  • 1
  • 1
Max
  • 31
  • 1
  • 2

2 Answers2

4

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.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
  • Thanks for your response. Unfortunately, the bash script and the process that runs indefinitely are pieces of a much bigger system that is more or less already implemented, so I'm really looking for solutions that rely soley on that. Basically, here is what I have: - Bash script with lots of logic to decide which processes to execute - some processes just run and that's it... others have while loops to have them run indefinitely until a key is pressed - I need other pieces of logic within bash script to find a certain running process later and give it a keypress to have it exit the while loop – Max Jun 26 '12 at 00:38
  • @Max: The Perl oneliner can be easily incorporated into a larger Bash script and, along with `pgrep` or `ps`, for example, which can find the process you should be able to do what you want. Did you actually *try* the Perl oneliner? Your question asked about sending a keystroke *not* about finding a process. – Dennis Williamson Jun 26 '12 at 01:10
0

what about just killing the process from a script

killall processname
Martin
  • 4,738
  • 4
  • 28
  • 57
  • The reason for the key press is because there is a while loop that runs until the key is pressed. There are certain things that need to run after the while loop is broken that are not accomplished by killing the process. – Max Jun 25 '12 at 23:12
  • @Max then why not have it listen for the kill signal, catch it, and use that to terminate the loop? Kill can send any signal you want it to, so you don't even need to use sigint. – Benubird May 22 '13 at 09:40