问题
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>
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>
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?
回答1:
pgrep -P <pid-of-new-urxvt>
gives the pid of the child zsh process.
Thx to @user1934428 for the brainstorming
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 "$@"
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.
来源:https://stackoverflow.com/questions/60698978/in-a-script-how-to-get-the-pid-of-spawned-terminals-shell-to-execute-commands-i