Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

358
Views
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)
{
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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;
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!