0

I want one parent and 4 childs and after creating them I print something like:

 [PID] (parent) with child processes: [PID1] [PID2] [PID3] [PID4]

and the parent waits for all of them to finish.

Could I use this code ( How to use Fork() to create only 2 child processes? ) in a loop or something like that?

I managed to do this:

      main()
{
    int pid, state, loop1=4, loop2, i=1, j;
    printf(" Parent before fork()\n"); 
    if ( ( pid=fork() ) !=0)
    {
        ParentPID=pid;
        wait( &state);
    }
    else
    {
        while(loop1!=0)
        {
            execl("child", 0);
            a[i]=pid;
            loop1--;
            i++;
        }
    }
    printf("Parent after fork()\n");
    for ( j=1; j<i; ++j )
    {
        printf ("PARENT_PID:"%d"  CHILD_PID[" %d "]= "%d,ParentPID, j, a[i]);
    }
    //printf("\tId process child=%d; finished with %d=%x\n",pid,state,state);
}

main()
{
    int pid;
    printf("Child: the execution starts \n");
    pid=getpid();
    printf("Child: %d execution finished\n", pid);
    exit( pid);
} 
Community
  • 1
  • 1
Marko
  • 407
  • 1
  • 7
  • 19
  • 1
    If you want X children then you need to call[`fork`](http://man7.org/linux/man-pages/man2/fork.2.html) X times *in the parent process*. If you do it separately or in a loop doesn't matter, the inportant part is that you do it in the parent process. – Some programmer dude Apr 05 '16 at 06:12
  • What do you mean by " in " the parent process? Could you please give me an example? – Marko Apr 05 '16 at 06:26
  • You do know what the [`fork`](http://man7.org/linux/man-pages/man2/fork.2.html) call returns? You do know how to check if you're in the parent or child process (or how to check if [`fork`](http://man7.org/linux/man-pages/man2/fork.2.html) failed)? – Some programmer dude Apr 05 '16 at 06:28
  • http://stackoverflow.com/questions/19461744/make-parent-wait-for-all-child-processes this thread might help you – Henningsson Apr 05 '16 at 06:49
  • Thank you, i have updated my code. – Marko Apr 05 '16 at 06:57
  • 1
    You are calling `fork` once, how many children do you expect to be created? – n. m. could be an AI Apr 05 '16 at 07:00
  • You'll need a loop to start the children, and another to wait for them to finish. You'll need an array to record the child pid values so that you can print the relevant information. You should handle errors from key system calls, especially if the `execl()` fails. – Jonathan Leffler Apr 05 '16 at 07:12
  • Thank you for the suggestions. I shall worry about error later, now I just wanna understand basics. I have updated my code again. What do you think? I dont know how to do the loop with the "wait" thing. :| – Marko Apr 05 '16 at 07:32
  • The posted code has two `main()` functions. There must be only one. The signature for `main()` always has a return type of `int`. What header files are #include'd? – user3629249 Apr 06 '16 at 20:37
  • strongly suggest reading/understanding the man page for the function `fork()` as the posted code is handling the returned value incorrectly. The posted code does not even try to output the line the OP stated they want output by the parent. – user3629249 Apr 06 '16 at 20:46
  • when system functions are called, handling an error needs to be the first thing you implement in the code. It will save you massive amounts of debug time when anything goes wrong. – user3629249 Apr 06 '16 at 21:25

1 Answers1

2

A solution could be:

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>

void childFunction(){
    printf("Child : %d\n", getpid());
    // do stuff
}

int main(){
    int childLimit = 3; // number of children wanted
    int childrenPids[childLimit]; // array to store children's PIDs if needed
    int currentPid, i;

    for(i=0; i<childLimit; i++){
        switch(currentPid = fork()){
            case 0:
                // in the child
                childFunction();
                // exit the child normally and prevent the child
                // from iterating again
                return 0;
            case -1:
                printf("Error when forking\n");
                break;
            default:
                // in the father
                childrenPids[i] = currentPid; // store current child pid
                break;
        }

    }

    printf("Father : %d childs created\n", i);

    // do stuff in the father

    //wait for all child created to die
    waitpid(-1, NULL, 0);
}

for more info see man waipid ;)

HenriC
  • 842
  • 8
  • 14
  • "wait for all child to die"... won't wait for ALL, the `waitpid()` call returns when any one of the child processes exits. – Ben Voigt Apr 05 '16 at 16:13
  • This answer does not output the line that the OP stated they want to ouput – user3629249 Apr 06 '16 at 20:42
  • @Monstercrunch: In the case structure, i dont think its ok that you catch the currentPid just for the default values. I want this info for every correctly created child. I believe the childrenPids[i] = currentPid statement should be in the case 0. – Marko Apr 11 '16 at 08:49
  • @Marko: in the case 0 the currentPid value is... 0 by definition. Fork() returns 0 if you are in the child, the child's pid otherwise (and -1 if an error occurs). – HenriC Apr 11 '16 at 09:02