Home > Net >  Does child process become parent process in c with fork?
Does child process become parent process in c with fork?

Time:11-13

I know that fork creates another process with the same code, and return 0 if you are in the child or pid of child if we are in the parent, but if that child process p1 creates another child p2, does p1 become a parent ?

#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include <errno.h>
#include <ctype.h>
#include <signal.h>
#include <sys/types.h>
 #include <sys/wait.h>
int main(int argc,char** argv){ 
   
   if(fork() == 0){
      if(fork() == 0){
         if(fork() == 0){
            printf("Output"); 
                  
         }     
      }
   }
   else{
       wait(NULL);
       
   }
   return 0;
}

So if thats correct the result should be just : Output ?

And why sometimes when i launch the program in Linux i get nothing and sometimes i get Output, what causes this inconsistency ?

CodePudding user response:

Yes, it's like a tree of ancestors.

int main(int argc, char *argv[]) {
    if (fork() == 0) {
        printf("Child process: %d\n", getpid());
        if (fork() == 0) {
            printf("Grandchild process: %d\n", getpid());
            if (fork() == 0) {
                printf("Great grandchild process: %d\n", getpid());
            }
        }
    } else {
        printf("Parent process: %d\n", getpid());
    }
    return 0;
}
  • Related