Looking at this post I do not understand Kaylum's answer. I have two questions.
1) S/he wants to use the variable "count" to count the total number of processes spawned (that is the total number of children grandchildren etc + original process) from a fork. I see that S/he starts off by setting count to 1 in the parent process which makes sense (to count the parent) but then S/he sets count to 1 again in the children. Why does this make sense? Count is already set to one and this only sets count equal to 1 again.
count += WEXITSTATUS(status);
2) I have been investigating WEXITSTATUS and from what I can gather it returns the exit status of a process through exit. My question is do I have to use
exit(0)
or
exit(1)
or something else for it to work. The documentation for this is not clear. In other words for it to work as Kaylum's
Full code segment here for convenience:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t before_pid, after_pid;
pid_t forked_pid;
int count;
int i;
int status;
before_pid = getpid();
count = 1; /* count self */
for (i = 0; i < 3; i++) {
forked_pid = fork();
if (forked_pid > 0) {
waitpid(forked_pid, &status, 0);
/* parent process - count child and descendents */
count += WEXITSTATUS(status);
} else {
/* Child process - init with self count */
count = 1;
}
}
after_pid = getpid();
if (after_pid == before_pid) {
printf("%d processes created\n", count);
}
return (count);
}