C/C++: Pass random value from parent to child after fork() via a pipe()


The following code will create a pipe for each child, fork the process as many times as it is needed and send from the parent to each child a random int value, finally the children will read the value and terminate.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char *argv[]) {
    int count = 3;
    int fd[count][2];
    int pid[count];
    srand(time(NULL));

    // create pipe descriptors
    for (int i = 0; i < count; i++) {
        pipe(fd[i]);
        // fork() returns 0 for child process, child-pid for parent process.
        pid[i] = fork();
        if (pid[i] != 0) {
            // parent: writing only, so close read-descriptor.
            close(fd[i][0]);

            // send the value on the write-descriptor.
            int r = rand();
            write(fd[i][1], &r, sizeof(r));
            printf("Parent(%d) send value: %d\n", getpid(), r);

            // close the write descriptor
            close(fd[i][1]);
        } else {
            // child: reading only, so close the write-descriptor
            close(fd[i][1]);

            // now read the data (will block)
            int id;
            read(fd[i][0], &id, sizeof(id));
            printf("%d Child(%d) received value: %d\n", i, getpid(), id);

            // close the read-descriptor
            close(fd[i][0]);
            //TODO cleanup fd that are not needed
            break;
        }
    }
    return 0;
}

This post is also available in: Greek

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.