Creating processes with Fork

Asked

Viewed 2,044 times

4

I am creating a sequence of processes through the command fork, but when I went to list the processes generated by the code, I found that there was a greater amount than I had created. Because of this?

In doing 10 forks were generated 1024 lawsuits.

#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 verify the amount of processes I used the ps:

ps aux | grep test_fork | grep -v grep | wc -l
  • instead of this pipeline you could have used "pgrep -c test_fork" :)

  • it’s a good idea tbm, I didn’t know how to use pgrep but I’ll look a little bit about it

  • after you learn about pgrep and pkill your problems are over :)

1 answer

5


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

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() the value returned will allow distinguish between parent (0) and child (case number). To avoid grandchildren, we 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
  • Very good answer! + 1 But it was good to also explain what the verification of pid == 0 does, not? :)

  • 1

    @Luizvieira, thanks again. I decided to reverse the logic to be easier to explain...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.