Child Process Creation through fork() in C -


i'm new c , learning processes. i'm little confused code below doing, it's taken wikipedia i've seen in several books , unsure why, example, pid_t pid; pid = fork();. reading seem suggest child process returns pid of 0, however, thought original parent process maintain pid of 0 after seeing tree root pid 0.

what does, example, pid = fork(); parent? doesn't same thing child? , doesn't pid = fork(); put loop each child?

basically, explain each step me if were, say, five? maybe younger? thanks!

#include <stdio.h>   /* printf, stderr, fprintf */ #include <sys/types.h> /* pid_t */ #include <unistd.h>  /* _exit, fork */ #include <stdlib.h>  /* exit */ #include <errno.h>   /* errno */  int main(void) {    pid_t  pid;     /* output both child , parent process     * written standard output,     * both run @ same time.     */    pid = fork();     if (pid == -1)    {       /* error:        * when fork() returns -1, error happened        * (for example, number of processes reached limit).        */       fprintf(stderr, "can't fork, error %d\n", errno);       exit(exit_failure);    }    else if (pid == 0)    {       /* child process:        * when fork() returns 0, in        * child process.        */       int  j;       (j = 0; j < 10; j++)       {          printf("child: %d\n", j);          sleep(1);       }       _exit(0);  /* note not use exit() */    }    else    {       /* when fork() returns positive number, in parent process        * (the fork return value pid of newly created child process)        * again count ten.        */       int  i;       (i = 0; < 10; i++)       {          printf("parent: %d\n", i);          sleep(1);       }       exit(0);    }    return 0; } 

upon successful completion, fork() (source):

  • shall return 0 child process
  • and shall return process id of child process parent process.

the example gave explained. however, precise both processes (parent , child) shall continue execute fork() function.

if know pid of child (from code of child), use getpid api.


Comments

Popular posts from this blog

asp.net mvc 3 - Using mvc3, I need to add a username/password to the sql connection string at runtime -

kineticjs - draw multiple lines and delete individual line -

thumbnails - jQuery image rotate on hover -