Search code examples
terminalpipestdinttyio-redirection

UNIX redirect tty to c++ stdin in different terminal


I have a simple command line c++ program shown below that takes stdin from the command line. I have 2 SSH terminals open on my Mac. One is /dev/ttys001 and one is /dev/ttys000. I want to echo a value in one terminal and have it be used at the stdin in the second terminal using my program. I can't seem to achieve this. What is the proper syntax? Thanks -

I've tried variations of the following but with no luck. In the terminal where I am running ./test, it prompts for the number and the echo from the other terminal definitely shows up on the console but it is not perceived by the program as stdin?

TERMINAL 1:

./test < /dev/ttys001

TERMINAL 2:

echo 2 > /dev/ttys001

My program:

#include <iostream>

using namespace std;

int main() {
    cout << "Enter a number: ";
    int nb;
    cin>>nb;
    cout << "Here is your number:" << nb << endl;
    return 0;
}

Solution

  • I'm not certain you can do it that way. However, you can use a named pipe. On terminal 1:

    mkfifo mypipe
    
    myprogram < mypipe
    

    Then on terminal 2:

    echo > mypipe
    

    Then type away. But your code looks like it will only execute once and then terminate, so you may want to add a loop.