Executing string sent from one terminal in another in Linux pseudo-terminal

前端 未结 4 1848
夕颜
夕颜 2021-01-29 08:57

Lets say I have one terminal where the output of \"tty\" is \"/dev/pts/2\" From another terminal, I want to send a command to the first terminal and execute it. Using: echo \"ls

4条回答
  •  醉话见心
    2021-01-29 09:39

    Usually getty, login, and shell programs are needed for executing commands from tty.

    But you can also put a shell directly executing commands from a pseudo terminal. This is simplified example (all error checkings removed):

    int main( int argc, char** argv )
    {
        int master_fd = create_my_own_psudo_terminal() ;
    
        // Wait until someone open the tty
        fd_set fd_rset;
        FD_ZERO( &fd_rset );
        FD_SET( master_fd, &fd_rset );
        select( master_fd + 1, &fd_rset, NULL, NULL, NULL );
    
        dup2( master_fd, STDIN_FILENO );
        execl("/bin/sh", "sh", 0 );
    
        return 0;
    }
    

    Now you can do the following:

    Start this simple program in the first terminal.

    And send your command from the second terminal:

    echo "ls" > /dev/pts/5
    

    And you will get listing in the first terminal.

    Note: This is quite unsecure, because login is not done.

提交回复
热议问题