09-24-04 10:51 PM
Jani Yusef wrote:
> I origially posted this in another group but this group is more
> appropriate so I am reposting it here.
> I am trying to create a tree of processes. The code below works,
> however, my initial call to the procTree function is passed depth-2. I
> arrived at this via trial and error and am not sure why this works?
> Can anyone spot what I am doing wrong? Or is that right for some reason
> I don't understand?
>
>
> int i=-1;
> int pid;
> int numberOfProcesses=-1;
>
> void procTree(int depth)
> {
> for(i=0;i<numberOfProcesses;i=i+1){
> int socko=socket(2,1,0);
> struct sockaddr_in addr;
> addr.sin_family=2;
> addr.sin_addr.s_addr=htonl((127<<24)+1);
> addr.sin_port=0;
> bind(socko,(struct sockaddr *)&addr,16);
> if((pid=fork())< 0){
> printf("Fork failed");
> exit(1);
> }
> if(pid==0){
> //then in child
> if(depth>0){
> procTree(depth-1);
> }
>
> // do other child stuff
> return;
> }
> if(pid){
> //then in parent
> }
> }
> }
>
> int main(int argc, char *argv[]){
> char input[MAXBUFFER];//create a character array to hold inpu
t
> from the user
> char output[MAXBUFFER];//create a character array to hold out
put
> int depth=atoi(argv[2]);
> numberOfProcesses=atoi(argv[1]);
>
> procTree(depth-2);
>
> read(0,input,MAXBUFFER);
> sprintf(output,"%s",input);
> write(1,output,strlen(output));
> }
>
> What I really really want to know is why I need to set depth to depth-2
> in my fist call to procTree? I just iteratated the value a few times to
> find one that works but I have no idea why!!
> I kept looking at ps output until the tree looked correct to me.
> i.e.
> $ ps -ef | grep "2 2"
> jani 2244 1979 0 15:34 ttyp1 00:00:00 ./a.out 2 2
> jani 2245 2244 0 15:34 ttyp1 00:00:00 ./a.out 2 2
> jani 2246 2244 0 15:34 ttyp1 00:00:00 ./a.out 2
>
In your code, you do not modify your depth value. Instead of saying
proctree(depth-1) say proctree(--depth).
--
Fletcher Glenn
[ Post a follow-up to this message ]
|