> Generally, if you want a tree you are looking at recurisive functions.
The logic is compilcated in this case because fork() spawns a child process,
and returns to both child and parent. Presumably you only want the children
to have children.
Note fork() isn't ANSI. However the problem is mainly C rather than UNIX, so
I'm answering it here.
void spawn(int depth, int nchildren)
{
int i;
if(depth == 0)
return;
/* terminate if parent */
if( fork() != 0)
return;
for(i=0;i<nchildren;i++)
spawn(depth-1, nchildren);
}
I tried your code and if I start with a depth of 2 and a number of
processes of 2 and then do a ps on my system I see 8 processes total.
Huh? Shouldn't I have just 3 processes?
Depth1 1
/\
/ \
Depth2 2 2
My code:
int i=-1;
int pid;
int numberOfProcesses=-1;
void spawn(int depth,int nchildren)
{
int i;
if(depth==0)
return;
/* terminate if parent */
if( fork()!=0){
}
for(i=0;i<nchildren;i++)
spawn(depth-1, nchildren);
}
int main(int argc, char *argv[]){
char input[MAXBUFFER];//create a character array to hold input
from the user
char output[MAXBUFFER];//create a character array to hold output
int depth=atoi(argv[2]);
numberOfProcesses=atoi(argv[1]);
spawn(depth,numberOfProcesses);
read(0,input,MAXBUFFER);
sprintf(output,"%s",input);
write(1,output,strlen(output));
}
After I run with arguments 2 and 2
$ps -ef | grep "2 2"
jani 2148 1979 0 15:24 ttyp1 00:00:00 ./a.out 2 2
jani 2149 2148 0 15:24 ttyp1 00:00:00 ./a.out 2 2
jani 2150 2148 0 15:24 ttyp1 00:00:00 ./a.out 2 2
jani 2151 2148 0 15:24 ttyp1 00:00:00 ./a.out 2 2
jani 2152 2149 0 15:24 ttyp1 00:00:00 ./a.out 2 2
jani 2153 2149 0 15:24 ttyp1 00:00:00 ./a.out 2 2
jani 2154 2152 0 15:24 ttyp1 00:00:00 ./a.out 2 2
jani 2155 2150 0 15:24 ttyp1 00:00:00 ./a.out 2 2