Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fork() in for() loop

Tags:

c

fork

I'm trying to make a homework assignment where I have to use fork() but I don't know why I can't stop my forks after running them through my for loop:

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

int main(int argc, char *argv[]){
    int limit = argc/2;
    if(argc%2 == 0){

            perror("the number of arguments given must pe even!");
            exit(1);
    }

    int i;
    for(i=0; i<=limit; i++){
        if(fork()==-1){
            perror("childes couldn't be created\n");
            exit(1);
        }
        if(fork()==0){
            printf("fork: %d \n",i);
            exit(1);
        }
        wait(0);
    }


    printf("exiting...\n");
    return 0;
}

Output:

warzaru@ubuntu:~/OS/UprocH$ ./exe a b c d
fork: 0 
fork: 0 
fork: 1 
fork: 1 
fork: 1 
fork: 2 
fork: 2 
fork: 1 
fork: 2 
exiting...
exiting...
fork: 2 
exiting...
exiting...
fork: 2 
exiting...
exiting...
exiting...
warzaru@ubuntu:~/OS/UprocH$ fork: 2 
fork: 2 
fork: 2 
exiting...
like image 629
Bogdan Maier Avatar asked May 03 '12 21:05

Bogdan Maier


People also ask

What happens when you fork in a loop?

fork() makes a copy of a process. If you do that in a "for" loop, you have a problem. The first time through the loop you invoke fork() and now you have two processes. Unless you have code to prevent it, both processes with continue to run that loop.

What is fork () used for?

fork() in C. Fork system call is used for creating a new process, which is called child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call.

How many processes are created by fork in for loop?

Each invocation of fork() results in two processes, the child and the parent. Thus the first fork results in two processes.


1 Answers

Daniel Fischer forced me to provide an answer.

Change:

if(fork()==-1){} // first fork
if(fork()==0){}  // second fork

To:

pid = fork();
if(pid == -1)
{
    ... //failed
}
else if(pid == 0)
{
    ... //success
}

Or use a switch statement:

switch(fork())
{
    case -1:
        ... // failed
        break;
    case 0:
        ... // success
        break;
}
like image 74
Daan Timmer Avatar answered Sep 26 '22 18:09

Daan Timmer