Inject Keystroke to different process using Bash

房东的猫 提交于 2019-12-18 05:13:13

问题


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.


回答1:


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.




回答2:


what about just killing the process from a script

killall processname


来源:https://stackoverflow.com/questions/11198603/inject-keystroke-to-different-process-using-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!