How to synchronize read and write in the pipe in C?

  c++, pipe

Complete C beginner here.
I am trying to write some strings from the child process and read the strings in the parent process. But it looks like I haven’t implemented the read and write properly. So my parent just reads the first string it gets. Below is my code

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <stdbool.h>
#include <ctype.h>

/* Function declaration */
bool isNumeric(char* str);


int main(int argc, char* argv[]) {
    // Check if input is recieved
    if (argc == 1) {
        printf("Input not received!n");
        exit(1);
    }
    // Check if the input is an int
    if (isNumeric(argv[1]) == 0) {
        printf("Input is not an Integer!n");
        exit(1);
    }

    // Initialize pipe
    int      fd[2];
    pid_t    childpid;

    pipe(fd);
    childpid = fork();

    if (childpid == -1) {
        printf("fork failed");
        exit(1);
    }
    else if (childpid > 0) {
            char string[100];
            close(fd[1]);
            printf("PARENT STARTn");
            while (read(fd[0], string, sizeof(string)) > 0) {
                    printf("%sn", string);
            }
            printf("PARENT ENDn");
            close(fd[0]);
    }
    else {
            close(fd[0]);
            char string[100];
            string[0] = '{$content}';
            printf("CHILD STARTn");
            for (int i = 0; i < 5; i++) {
                    sprintf(string, "%d", i);
                    write(fd[1], string, strlen(string)+1);
            }
            printf("CHILD ENDn");
            close(fd[1]);
            exit(0);
    }
}

The output is just

PARENT START
CHILD START
CHILD END
0
PARENT END

My expected output is

PARENT START
CHILD START
CHILD END
0
1
2
3
4
PARENT END

I spent hours trying to synchronize the process, but I couldn’t figure out how to fix the problem.

Source: Windows Questions C++

LEAVE A COMMENT