I wrote a program that creates 3 children for a process.
Then, each children create 3 processes as well.
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <stdbool.h>
#define GENERACIONES 2
void crearHijo(int, int);
int main()
{
int i;
for (i = 1; i <= 3; i++)
crearHijo(i, 1);
return 0;
}
void crearHijo(int hijoNum, int gen)
{
pid_t pid = fork();
int i, hijos = 3;
if (pid < 0)
{
fprintf(stderr, "Fork Failed");
exit(-1);
}
else if (pid == 0)
{
printf("Soy de la generación %d, hijo # %d, PID: %d, PPID: %d\n",
gen, hijoNum, getpid(), getppid());
if (gen < GENERACIONES)
{
gen++;
/*srand(time(NULL));
hijos = rand() % 3 + 1;*/
for (i = 1; i <= hijos; i++)
crearHijo(i, gen);
}
exit(0);
}
else
waitpid(pid, NULL, NULL);
}
I’m expecting 3 sons and 9 grandsons.
But I get the following output:
Soy de la generación 1, hijo # 1, PID: 2533, PPID: 2532
Soy de la generación 2, hijo # 1, PID: 2534, PPID: 2533
Soy de la generación 1, hijo # 1, PID: 2533, PPID: 2532
Soy de la generación 2, hijo # 2, PID: 2535, PPID: 2533
Soy de la generación 1, hijo # 1, PID: 2533, PPID: 2532
Soy de la generación 2, hijo # 3, PID: 2536, PPID: 2533
Soy de la generación 1, hijo # 1, PID: 2533, PPID: 2532
Soy de la generación 1, hijo # 2, PID: 2537, PPID: 2532
Soy de la generación 2, hijo # 1, PID: 2538, PPID: 2537
Soy de la generación 1, hijo # 2, PID: 2537, PPID: 2532
Soy de la generación 2, hijo # 2, PID: 2539, PPID: 2537
Soy de la generación 1, hijo # 2, PID: 2537, PPID: 2532
Soy de la generación 2, hijo # 3, PID: 2540, PPID: 2537
Soy de la generación 1, hijo # 2, PID: 2537, PPID: 2532
Soy de la generación 1, hijo # 3, PID: 2541, PPID: 2532
Soy de la generación 2, hijo # 1, PID: 2542, PPID: 2541
Soy de la generación 1, hijo # 3, PID: 2541, PPID: 2532
Soy de la generación 2, hijo # 2, PID: 2543, PPID: 2541
Soy de la generación 1, hijo # 3, PID: 2541, PPID: 2532
Soy de la generación 2, hijo # 3, PID: 2544, PPID: 2541
Soy de la generación 1, hijo # 3, PID: 2541, PPID: 2532
Some entries are duplicated and I don’ understand why.
There are not more than 12 processes but some of them print the output several times.
How can I avoid this behavior?
TIA
When your:
is done on the child process, the function returns and the main’s
is continued
Try something like this: