0

I am using pipe in an IPC communication between a parent and child. Child using stdout to send messages. while parent is blocked at read function.

The problem is child doesn't send the message one by one. it send some of them together at the same time when it reaches some size (4096 charcter i think).

here is my read function:

void waitMessage(int id,char* buffer,int* size,struct Pipe * pipes){
    printf("waiting %d\n",id);
    char c = '\0';
    int i = 0;
    fprintf(stderr,"recieved: ");

    fcntl( pipes[id].fd[0][0], F_SETFL, fcntl(pipes[id].fd[0][0], F_GETFL) | O_NONBLOCK);

    int res = -1; 
    while(res == -1) 
        res = read(pipes[id].fd[0][0],&c,1);

    while(res != -1){
        buffer[i] = c;
        printf("%c",buffer[i]);
        i++;
        res = read(pipes[id].fd[0][0],&c,1);
    }
    (*size) = i;
    printf("\n");
}
  • please ignore my non-blocking usage of the function
Antoun
  • 115
  • 6
  • If the problem is the child, you should post the code where the child writes the message – Karsten Koop Sep 20 '18 at 11:05
  • child uses stdout. It is just printf("%s",msg); – Antoun Sep 20 '18 at 11:11
  • 2
    Did you try flushing stdout? c.f. [this question](https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin) – Karsten Koop Sep 20 '18 at 11:13
  • Thanks a lot. It solved my problem – Antoun Sep 20 '18 at 11:16
  • 1
    Note that a pipe is not an interactive device, so standard output might be fully buffered in the child rather than line buffered. That means that even adding a newline may not force a message to the pipe (though it might); you need to use `fflush()` to ensure that a message is sent once complete. – Jonathan Leffler Sep 20 '18 at 14:36

0 Answers0