• Uncategorized

About c : Reading-the-input-stream-of-another-process-in-C

Question Detail

I want to view the input stream of a C program using a secondary program to access it.
I tried passing the STDIN from one process to the other using a FIFO (I’m on Linux) and viewing the size of the stream on the second program but it gives a segmentation fault.

First program (writes to the FIFO):

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(){

    int fd;
    char c;

    fd = open("myfifo",O_WRONLY);

    if(fd == -1){
        printf("Couldn\'t open FIFO");
        return 0;
    }

    write(fd,&stdin,sizeof(FILE *));
    
    while((c = getchar()) != EOF) {  }

    printf("\n");
    
    close(fd);

}

Second program (reads from the FIFO):

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(){

    int fd;
    char c;
    FILE *inptr; 

    fd = open("myfifo",O_RDONLY);

    if(fd == -1){
        printf("Couldn\'t open FIFO");
        return 0;
    }

    read(fd,&inptr,sizeof(FILE *));

    close(fd);

    int size = 0;

    while(1){

        system("clear");

        fseek(inptr, 0, SEEK_END);
        size = ftell(inptr);
        fseek(inptr, 0, SEEK_SET);

        printf("<%d>",size);

        sleep(1);

    }    

    printf("\n");

}

Question Answer

Usually, you can’t do quite anything to another process: the operating system forbids it, on purpose. They are all isolated from each other.

What you search is to tee the first process output to both second program input, AND add a third process to read it too. So you should look at man tee and launch your two process using tee – then you’ll be able to spy what is sent. But you should do it from the shell, or “hack” how one of the two process launch the other in order to do the same programmatically.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.