0

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?

philipper
  • 373
  • 3
  • 11
  • After `urxvt &`, `$!` contains the PID of the urxvt process. The zsh you are looking for, is a child process of this. Use the `ps` command to get a list of all processes, and pick a line which is a zsh process having the PPID which you have just found. – user1934428 Mar 16 '20 at 08:51
  • Sure. I did that manually and it works. But I want to be able to do this in a script. – philipper Mar 16 '20 at 21:45
  • 1
    Which part of what do you manually, can't be automatized? You have the pid, you have the output of `ps` .... now just write a program which searches the pid in the whole process list. It's just a text search. You can do it in virtually any language you like; doesn't even have to be bash. – user1934428 Mar 17 '20 at 08:30
  • Agreed but it seems like such a trivial problem I'm hoping there is a cleaner solution – philipper Mar 18 '20 at 00:34

1 Answers1

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.

philipper
  • 373
  • 3
  • 11