Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differentiate child processes?

Say I fork N children. I want to create pipes between 1 and 2, 2 and 3, 4 and 5, ... and so on. So I need some way to figure out which child is which. The code below is what I currently have. I just need some way to tell that child number n, is child number n.

int fd[5][2];
int i;
for(i=0; i<5; i++)
{
    pipe(fd[i]);
}
int pid = fork();
if(pid == 0)
{
}
like image 895
Brian Crafton Avatar asked Feb 01 '26 11:02

Brian Crafton


1 Answers

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 an int value (the id we want to give to the child), finally the children will read the value and terminate.

Note: since you are forking, the i variable will contain the iteration number, if the iteration number is the child id, then you do not need to use pipe.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    int count = 3;
    int fd[count][2];
    int pid[count];

    // 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 childID on the write-descriptor.
            write(fd[i][1], &i, sizeof(i));
            printf("Parent(%d) send childID: %d\n", getpid(), i);

            // 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));
            // in case the id is just the iterator value, we can use that instead of reading data from the pipe
            printf("%d Child(%d) received childID: %d\n", i, getpid(), id);

            // close the read-descriptor
            close(fd[i][0]);
            //TODO cleanup fd that are not needed
            break;
        }
    }
    return 0;
}
like image 60
George Michael Avatar answered Feb 03 '26 03:02

George Michael