Created
September 22, 2019 00:40
-
-
Save MasterGeekMX/287490d3f992ecc5b7a62b134ab2d2cd to your computer and use it in GitHub Desktop.
C code to spawn a binary tree of processes using fork(). Tree depth is set by a variable passed as first argument at invocation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/types.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
void tree(int n){ //Creates a process tree | |
if (n==0) return; //We have reached a leaf, so we leave. | |
int rchild=fork(); //create right child | |
if (rchild!=0){ //we are the parent | |
int lchild=fork(); //create left child | |
if (lchild==0) tree(n-1); //we are the left child, so we create the left subtreee | |
} | |
else{ //we are the right child | |
tree(n-1); //create the right subtree | |
} | |
} | |
int main(int argc, char **argv){ | |
if (argv[1]==NULL) return 1; //we need the depth in order to proceed | |
int n=atoi(argv[1]); //conversion of the first parameter to an ineger | |
if (n==0) return 0; //if the depth is zero, there is nothing to do | |
tree(n); //create a tree of depth n | |
sleep(1000); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment