Search code examples
cforkpidmultiple-processes

how to run multiple children with different tasks?


My program has to create multiple children, i take the number of children from terminal. Then, I need to group them and every group has different tasks.

I created the children but the problem is that I can't give them separated tasks, I can't distinguish children. Only thing I can do is, every children works on the same part(like printing pids).

How can I separate them and give them specific tasks?

For example, first 4 children should call a function, other 3 should print something and other 3 should write to a file etc.

    pid_t pid[10];

    pid[0] = fork();
    if(pid[0] > 0)
    {
        for(int i = 0; i < 9; i++)
        {
            if(pid[i] > 0)
            {
                pid[i + 1] = fork();
            }
        }
    }

    for(int i = 0; i < 10; i++)
    {   
        if(pid[i] == 0)
        {
            printf("child %d, parent %d\n", getpid(), getppid());
            exit(1);
        }
    }

Solution

  • I think you should take a look at how the fork() function works. Here is the man page, here a useful answer and here a useful tutorial.

    When you use fork() in your code, know that the child process continue from where the parent was. So when you call fork() in the first for loop, all the child processes continue the loop that the parent has begun. I don't think this is the behavior you expect.

    Anyway, here's a possible solution for your problem. In this way your processes do some stuff divided in small groups. Note the exit(0) function at the end of the work. It is important to be sure that every process does only its work and not also its parent's work:

    pid_t pid[10];
    
    for (int i = 0; i < 9; i++)
    {
        pid[i] = fork();
    
        //First group            
        if (pid[i] == 0 && i < 4){
            //Insert here the code for the first group or call a fuction
            exit(0);
        }
    
        //Second group
        if (pid[i] == 0 && i >=4 && i < 8){
            //Insert here the code for the second group or call a fuction
            exit(0);
        }
    
        //Third group
        if (pid[i] == 0 && i >=8){
            //Insert here the code for the third group or call a fuction
            exit(0);
        }
    
        if (pid[i] < 0){
            perror("Something wrong with the fork");
            exit(1);
        }
    }