Question

I'm just new to the piping I/O functions within Linux. 2 c-files were made, the first sends data:

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

    int main(int argc, char* argv[])
    {
         int i = 0;

         for(;;)
         {
             printf("\nSent number: %d",i);
             i++;
             sleep(1);
             fflush(stdout);
         }

    return 0;
}

The second files receives the printed number and displays it:

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

int main(int argc, char* argv[])
{    
    int x;

    for(;;)
    {
        scanf("%d",&x);
        printf("Received number: %d\n",x);
        sleep(1);
        fflush(stdout);
    }

    return 0;
}

Finally I try to redirect the data from the first file to the second with:

./send_test.out | ./rcv_test.out

The Terminal prints repeatedly: "Received number: 0", what am I doing wrong? Also, how can I have to terminal windows for both programs running simultaneously while directing the output from the sender to the receiver?

Thanks in advance

Was it helpful?

Solution

You are not "sending" the number in a format the the receiver can understand.

Try removing all text except the %d from the sender's formatting string.

Also, you should check the return value of scanf() before relying on it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top