Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I forking more than 5 times here?

Tags:

c

fork

So I have code here, and I expected it to strictly run ls -l 5 times, but it seems to run far more times. What am I doing wrong here? I want to run ls 5 times, so I fork 5 times. Perhaps I don't understand the concept of wait properly? I went over a ton of tutorials, and none seem to tackle multiple processes using fork thoroughly.

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

int main()
{
    pid_t pidChilds[5];

    int i =0;

    for(i = 0; i<5; i++)
    {
        pid_t cpid = fork();
        if(cpid<0)
            printf("\n FORKED FAILED");
        if(cpid==0)
            printf("FORK SUCCESSFUL");
        pidChilds[i]=cpid;
    }





}
like image 936
NoNameY0 Avatar asked Mar 07 '13 14:03

NoNameY0


1 Answers

You are forking in a loop and fork quasi-copies the process including the instruction-pointer.

Meaning: eg your first child-process will find itself in a loop that still has 4 rounds to go.

And each of the 4 processes that process spawns will find it has to go 3 rounds more.

And so on.

fork() returns whether the process you are in is the parent- or child-process. You should check that return value and break; the loop if you are in a child-process.

" On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately. "

So you should if(cpid==0) break;.

like image 93
Bernd Elkemann Avatar answered Sep 24 '22 18:09

Bernd Elkemann