c - Count number of processes created using fork in a for loop -
i trying find way count number of processes created in loop of length 10 fork() call. easy see result 2^n n calls, need way compute in program.
i have found identical question in here. however, when tested second solution given here, works ok number of forks less 10. 10, yelds 256. why that? , there solution problem? (apart using pipes). here actual code:
for(i=1; i<=10; i++) {     fork();     printf("the process pid=%d\n", getpid()); }      
there 1 byte exit status of process.  therefore, cannot count higher 255 via process exit codes.  furthermore, quirk of specific algorithm tried happens produce maximum possible exit status (to parent process adds 1 256).  exit() function uses least significant 8 bits of argument (and returning x main() has same effect calling exit(x)).
to count higher, need different approach. establish counter in shared memory, , have each child process increment (with appropriate synchronization). runs cleanly, shared memory not trivial work with. have each process append file leave record; parent process read file count how many processes left such record.
Comments
Post a Comment