简体   繁体   中英

C process and forking process

Im studying Operative Systems and can't really grasp this piece of code:

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

int main() 
{
    int pid;
    int i;

    pid = fork();

    switch(pid)
    {
        case -1: 
            perror ("Error \n");
            break;

        case 0: 
            for(i=1; i < 11; i++)
                printf ("Im the son %d, My father is %d - Loop %d \n", getpid(), getppid(), i);
            break;

        default: 
            for(i=1; i < 11; i++)
                printf ("Im the father %d and my father is %d - Loop %d \n", getpid(), getppid(), i);

            wait(NULL);
            printf("End of the father process %d - My son process %d have finished.\n", getpid(), pid);
            break;
    }

}

I understand that you fork (create a duplicate of the process), if everything went fine (different from -1) then it loops in a for ten times and then breaks, what I dont understand is how the son can go back to the for , I mean if it is 0 (the son) the you printf "it's the son X and my father is Y" and then breaks. how is it that it loops both of them 10 times?.

for() without {} only executes the next line repeatedly.

for(i=1; i < 11; i++)
    printf();
break;

is the same as

for(i=1; i < 11; i++) {
    printf();
}
break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM