Creating processes with fork

4

I'm creating a sequence of processes through the command fork , but when I was listing the processes generated by the code, I came across that there was a larger amount than I had created. Why this?

  

By 10 forks 1024 processes were generated.

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

int main(int argc, const char **argv){
    int fork_id[10];
    int x;
    for(x=0; x<10; x++){
        fork_id[x] = fork();
        if(!fork_id){
            execl("/usr/bin/sleep", "5", NULL);
        }
    }

    sleep(10);

    return 0;
}

To check the number of processes I used ps :

ps aux | grep test_fork | grep -v grep | wc -l
    
asked by anonymous 28.01.2017 / 05:22

1 answer

5

In reality your solution is generating 2 ^ 10 processes (since each child with x = n will create still grandchildren (with x = n + 1 ... x = 10), and these great grandchildren, etc.)

I proposed:

int main () {
    int i, pid;
    for (i = 0; i < 10; ++i) {
        pid = fork();
        if (pid != 0) { //se sou o processo filho: saio do ciclo!
            break;
        }
    }
    printf("I am : (i=%d),(pid=%d) mypid=%d\n",i, pid, getpid());
    return 0;
}

That is, when the fork() is done the value returned will allow distinguish between parent (0) and child (case number). To avoid grandchildren, we've put together an instruction that says:

Se eu sou o filho, sai do ciclo para não haver netos...

What gives:

I am : (i=0),(pid=25794) mypid=25793
I am : (i=1),(pid=25795) mypid=25794
I am : (i=2),(pid=25796) mypid=25795
I am : (i=3),(pid=25797) mypid=25796
I am : (i=4),(pid=25798) mypid=25797
I am : (i=5),(pid=25799) mypid=25798
I am : (i=6),(pid=25800) mypid=25799
I am : (i=7),(pid=25801) mypid=25800
I am : (i=8),(pid=25802) mypid=25801
I am : (i=9),(pid=25803) mypid=25802
I am : (i=10),(pid=0) mypid=25803
    
28.01.2017 / 12:44