0

Could a program read() information from the terminal output using STDOUT_FILENO file descriptor instead of STDIN_FILENO?

I made some example:

void auxiliar_alrm() {
    write(STDIN_FILENO, "Hello!\n", strlen("Hello\n"));
}

int main() {

    signal(SIGALRM, auxiliar_alrm); 

    alarm(3);

    char word[100];
    read(STDOUT_FILENO, word, 100); //Program gets blocked here till a SIGALRM prints something on screen

    //...
}

After that read(), word will store what the write in the signal handler has written to the screen?

I tried this code and it doesn't work, but I'm wondering if I'm missing something to get this work.

user157629
  • 624
  • 4
  • 17
  • Does this answer your question? [Is it possible to read from stdout?](https://stackoverflow.com/questions/34966914/is-it-possible-to-read-from-stdout) –  Jan 10 '21 at 13:47
  • 1
    No you cannot - it does not make even sense to be able to write read (or is that scribbling over the book!) – Ed Heal Jan 10 '21 at 13:47
  • Sounds like you're looking for a pipe. – Shawn Jan 10 '21 at 14:04
  • You cannot read from a terminal what you wrote to that terminal. If STDOUT_FILENO and STDIN_FILENO both refer to a terminal, then writing to STDIN_FILENO has exactly the same effect as writing to STDOUT_FILENO, i.e. you just write stuff to your terminal. – n. m. could be an AI Jan 10 '21 at 14:22

1 Answers1

1

Create a pipe to pass the data

static int pipe_fd[2];

void auxiliar_alrm() {
    write(pipe_fd[1], "Hello!\n", strlen("Hello\n"));
}

int main() {
    if (pipe(pipe_fd) == -1) {
        return 1; //failed to create pipe
    }

    signal(SIGALRM, auxiliar_alrm); 

    alarm(3);

    char word[100];
    read(pipe_fd[0], word, 100);

    //...
}

pipe creates two file descriptors, one for reading (index 0) and one for writing (index 1) to/from the create pipe.

koder
  • 2,038
  • 7
  • 10