0

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

user3488736
  • 109
  • 1
  • 3
  • 13

1 Answers1

0

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • That did the trick, thanks! How can I run both programs simultaneously on 2 different Terminal windows though? – user3488736 Apr 14 '14 at 08:39
  • 1
    You could make a FIFO for the two programs to send data through. Type "mkfifo pipe", then run "./program1 > pipe" and in a different window run "./program2 < pipe" – Mark Setchell Apr 14 '14 at 08:46