Also versuche ich das Konzept der Enkelkinder zu verstehen. Ich kann eine bestimmte Anzahl von Söhnen (d. H. Brüder) erstellen, aber ich weiß nicht, wie mehrere Generationen erstellt werden. Diese ist das, was ich tat, ein Enkel zu erstellen:Erstellen Sie mehrere Generationen von Kindern Prozess
int main()
{
//Displaying the father
printf("Initial : Father = %d\n\n", getpid());
/****** FORK *******/
pid_t varFork, varFork2;
varFork = fork();
if(varFork == -1) //If we have an error, we close the process
{
printf("ERROR\n");
exit(-1);
}
else if (varFork == 0) //if we have a son, we display it's ID and it's father's
{
printf("SON 1\n");
printf(" ID = %d, Father's ID = %d\n", getpid(), getppid());
varFork2 = fork();//creation of the second fork
if(varFork2 == -1) //If we have an error, we close the process
{
printf("ERROR\n");
exit(-1);
}
else if (varFork2 == 0) //now we have the son of the first son, so the grandson of the father
{
printf("\nGRANDSON 1\n");
printf(" ID = %d, Father's ID = %d\n", getpid(), getppid());
}
else sleep(0.1);/*we wait 0.1sec so that the father doesn't die before we can
display it's id (and before the son process gets adopted by a user process descending from the initial process)*/
}
else //in the other case, we have a father
{
sleep(0.1);//again we put the father asleep to avoid adoption
}
return 0;
}
Wie kann ich X Generationen von Enkeln, X eine globale Variable sein (1son, 1 Enkel, 1 Urenkel, etc.)?
OT: 'sleep()' nimmt eine ganze Zahl. Aufgrund der impliziten Typumwandlung 'sleep (0.1)' ergibt sich 'sleep (0)' – alk
'printf (" Error \ n ")' ist fast immer * falsch *. Und mit "fast immer" meine ich immer. Es gibt einen Grund, dass die Unix-Konvention Prozesse mit 3 offenen Dateideskriptoren startet, und Sie sollten sich angewöhnen, sie alle zu verwenden. Fehlermeldungen sollten sowohl sinnvoll als auch in den richtigen Stream geschrieben sein. 'fprintf (stderr," Error \ n ")' –
Um Nachrichten bedeutungsvoll zu machen, 'man perror' –