在脚本中,如何使用ttyecho获取派生终端的shell的pid以便在其中执行命令? [英] In a script how to get the pid of spawned terminal's shell to execute commands in it using ttyecho?
问题描述
我正在使用ttyecho(可以与 yay -S ttyecho-git
一起安装)在单独的终端中执行命令,如下所示:
I am using ttyecho (can be installed with yay -S ttyecho-git
) to execute a command in a separate terminal like so:
urxvt &
sudo ttyecho -n /proc/<pid-of-new-urxvt>/fd/0 <command>
它不起作用,因为/proc/pid-of-new-urxvt/fd/0是指向父终端的/dev/pts/x的符号链接.在生成的urxvt中,我碰巧运行zsh.因此,如果我使用该zsh进程的pid,它将起作用:
It does not work because the /proc/pid-of-new-urxvt/fd/0 is a symlink that points to the /dev/pts/x of the parent terminal. In the spawned urxvt I happen to run zsh. So if I use the pid of that zsh process it works:
sudo ttyecho -n /proc/<pid-of-new-zsh-within-new-urxvt>/fd/0 <command>
当运行 urxvt&
时,如何获取在新urxvt进程中生成的新zsh进程的pid?还是有不同的解决方案来实现相同的结果?
How can I get the pid of the new zsh process spawned within the new urxvt process when I run urxvt &
? Or is there a different solution to achieve the same result?
推荐答案
pgrep -P< pid-of-new-urxvt>
给出子zsh进程的pid.感谢@ user1934428进行头脑风暴
pgrep -P <pid-of-new-urxvt>
gives the pid of the child zsh process.
Thx to @user1934428 for the brainstorming
这是生成的bash脚本:
Here is the resulting bash script:
urxvt &
term_pid=$!
# sleep here makes us wait until the child shell in the terminal is started
sleep 0.1
# we retrieve the pid of the shell launched in the new terminal
shell_pid=$(pgrep -P $term_pid)
# ttyecho executes the command in the shell of the new terminal and gives back control of the terminal so you can run further commands manually
sudo ttyecho -n /proc/${shell_pid}/fd/0 "$@"
因此,当我启动脚本ls"时,它将打开一个新终端,运行ls,并在终端仍处于打开状态的情况下返回提示.我只需要在sudoers文件中添加ttyecho.
So when I launch "script ls" it opens a new terminal, runs ls, and gives back the prompt with the terminal still open. I just had to add ttyecho in the sudoers file.
这篇关于在脚本中,如何使用ttyecho获取派生终端的shell的pid以便在其中执行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!