cposixstdout

Can I read() from STDOUT_FILENO?


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.


Solution

  • 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.