Copy the above code to some C file (For eg. tty-send-command.c). Run the following command in the directory you have created the C file in to compile the code.

make tty-send-command

Copy this file to the bin directory.

Start another terminal or switch to any other open terminal that you wish to control and execute the command tty. You can see a sample output below.

@~$ tty
/dev/pts/4

Now to execute a command on /dev/pts/4, run the following command in the controlling/original terminal.

sudo tty-send-command -n /dev/pts/4 echo "Hello there"

You will see that the ls command is executed in /dev/pts/4. The -n option makes tty-send-command send a newline after the command, so that the command gets executed and not just inserted. This utility can infact be used to send any data to other terminals For eg, you could open vim in /dev/pts/4 and then run the following command in the controlling terminal to cause vim to exit in /dev/pts/4.

sudo tty-send-command -n /dev/pts/4 :q

To avoid using sudo all the time, so that the command is easily scriptable, change the owners/permissions of this executable using the following commands.

sudo chown root:root tty-send-command
sudo chmod u+s tty-send-command

What we did was change the owner/group to root and set the setuid bit for the executable which will allow you to run the utility with root permissions.