Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does child process become parent process in c with fork?

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading