InsaneCoder
InsaneCoder

Reputation: 8268

Linux : pipeline output of one program to another

I have made two simple programs :

out.c

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int x;
    srand((unsigned int)time(NULL));
    for(;;)
    {
        x = rand();
        printf("%d\n", x % 100);
        sleep(1);
    }
    return 0;
}

in.c

#include <stdio.h>

int main()
{
    int x;
    for(;;)
    {
        scanf("%d",&x);
        printf("%d\n", x);
    }
    return 0;
}

I am running it like ./out | ./in , but i am not getting any print. What's the correct way to run in such a way as to pipeline the inputs

Upvotes: 1

Views: 33

Answers (1)

Adrian
Adrian

Reputation: 15171

This problem can be fixed by flushing stdout in your out.c program. You need to do this because it doesn't automatically get flushed if stdout isn't a tty, depending on your operating system.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int x;
    srand((unsigned int)time(NULL));
    for(;;)
    {
        x = rand();
        printf("%d\n", x % 100);
        fflush(stdout); // <-- this line
        sleep(1);
    }
    return 0;
}

Upvotes: 1

Related Questions