Skip to content

Instantly share code, notes, and snippets.

@fernandozamoraj
Created October 26, 2020 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fernandozamoraj/0f2b85514852d6aa77da31d8cbc627f6 to your computer and use it in GitHub Desktop.
Save fernandozamoraj/0f2b85514852d6aa77da31d8cbc627f6 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
//this code must be run in an unix env
int main(int argc, char *argv[]){
pid_t pid;
//get parent pid before the fork
//getpid will change for child after fork
//the parent will still have the same pi
pid_t parentPid = getpid();
fork();
pid = getpid();
//do sometihng in the child proces
if(pid != parentPid){
printf("\nHello from child process pid %d", pid);
}
//do something in the parent process
if(pid == parentPid){
printf("\nHello from parent process pid %d", pid);
}
printf("\nhello world from both... one each in the fork\n");
fork();
pid_t gpid = getpid();
if(gpid != parentPid && gpid != pid)
printf("\nHello from the grandchildren %d\n", gpid);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment