Search code examples
clinuxprocessfork

C creating processes with Fork()


  int main()
{
     int i;
     int status;

     for (i = 0; i < 4; i++) {
         if(fork() == 0){
             sleep(1);
         }
     }

     printf("This is the end.\n");
     
     return 0;
} 

I need to change the code so that exactly 4 child processes will be created. I have tried a few things but Im not sure how to do it.


Solution

  • You have to prevent the child processes from creating new child processes. To do so, just exit the loop in a child process.

    for (i = 0; i < 4; i++) {
        if(fork() == 0) {
            // Only the child process will execute this
            sleep(1);
            break;
        }
    }