2

I want to send strings from child process to another child process with pipes. Could someone explain me why it works with "printf("NOW IT WORKS\n")" but doesn't work then printf is deleted ?

int main()
{

    char bufp1[100];
    char bufp2[100];
    char bufp2i;
    int pipe1[2],pipe2[2];
    int id_p1, id_p2;
    if(pipe(pipe1)<0)return 1;
    if(pipe(pipe2)<0)return 1;


    switch(id_p1=fork())
    {
        case 0:
            {
            close(pipe1[0]);
            printf("PP1 %d\n",getpid());        
            for(;;)
            {
                scanf("%s",&bufp1);     
                write(pipe1[1],bufp1,100);  
            }
            break;
            }
        case -1:
            printf("error 1\n");
            exit(1);
    }

    switch(id_p2=fork())
    {
        case 0:
            {
            close(pipe1[1]);
            printf("PP2 %d\n",getpid());
            for(;;)
            {
                //printf("NOW IT WORKS\n");
                read(pipe1[0],bufp2,100);
                bufp2i=strlen(bufp2);
                printf("%i",bufp2i);
            }
            break;
            }
        case -1:
            printf("error 2\n");
            exit(1);
            break;
    }
    for(;;);

    return 0;

}
Cichy
  • 21
  • 4
  • add `\n` in the `printf("%i",bufp2i);` to write the line. – Kami Kaze Feb 14 '17 at 13:55
  • Thank you, but I want to understand why it is happening, not a temporary solution. – Cichy Feb 14 '17 at 13:57
  • this is not a temporary solution but the way to write standard compliant code. If this solved the problem, then you should remember to always end a `printf()` with`\n` so it is guaranteed to really print the output otherwise it might be stuck in the buffer. If this hasn't solved the problem there might be more wrong in your code, but the above is still true. – Kami Kaze Feb 14 '17 at 14:01
  • You can read up the specifics here: http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin . Did this fix your problem entirely? – Kami Kaze Feb 14 '17 at 14:03
  • Yes it helped. Thank you very much ! – Cichy Feb 14 '17 at 14:20

0 Answers0