1

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

Naveen
  • 7,944
  • 12
  • 78
  • 165
  • This is one link I found, http://unix.stackexchange.com/questions/40277/is-there-a-way-to-pipe-the-output-of-one-program-into-two-other-programs, but i don't think that is relevant in this case. – Naveen Oct 24 '15 at 17:42
  • http://stackoverflow.com/questions/2784500/how-to-send-a-simple-string-between-two-programs-using-pipes – Jrican Oct 24 '15 at 17:54

1 Answers1

1

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;
}
Adrian
  • 14,931
  • 9
  • 45
  • 70