HI there,
I am trying to count manually what this code does but I am stuck and I don't learly see the result. The code works and it compiles and runs but I just don't follow the value of var.
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<wait.h>
int main (int argc, char *argv[]){
int var = 0;
pid_t p;
while(++var <5){/*as long as it is less than this it will do fork*/
if((p=fork()) < 0){
perror("fork error");
exit(1);
}else if(p ==0){ /*if it is the child*/
var--; /*count down*/
}
else{
if(waitpid(p,NULL,0) != p){/*if waipid is not equal p*/
perror("waitpid error");
exit(1);/*exit with status signal1*/
}/*end if*/
var++;
} /*end if/else*/
var++;
}/*end while*/
printf("pid=%d, ppid=%d var=%d, p=%d\n", getpid(), getppid(), var, p);
exit(0);
}/*end main*/
I understand that in the while condition it says that it should not do something more than 4 times in this case it will fork 4 times. Then in the second if statement it says that if p is the child then we count down (var--) but and yet again at right before closing the while statement we use the counter (var++) again does this mean that whatever was added in the beginning to (++var) at the beginning of the loop then gets subtracted (--var) in the if statement and then added again (var++) just before while?. I cannot follow, can someone give me some insight into how counting the loop and what the code does?
BR,
Bluetxxth
so I am drawing now..