1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| #include <stdio.h>
#include <sys/types.h> // pour pid_t
#include <unistd.h> // pour fork(), getpid(), getppid()
#include <sys/wait.h> // pour wait()
#define NBR_FILS 2
int main (void)
{
pid_t fils[10];
pid_t pere = getpid();
int i=0;
// Generation des fils
for(i=0;i<NBR_FILS;i++)
{
fils[i] = fork();
if(getpid() != pere)
break;
// Traitement lors du fork
if(fils[i]<0)
{
fprintf(stderr,"Fork impossible");
return -1;
}
}
// Determination en fonction de la place genealogique
pid_t pid = getpid();
if (pid==pere)
{
fprintf(stdout, "Je suis le pere, monsieur %d\n", pere);
// Attendre tous les fils
for(i=0;i<NBR_FILS;wait(NULL),i++)
;
fprintf(stdout, "Tous mes fils sont termines");
return 1;
} else if (pid!=pere)
{
fprintf(stdout,"Je suis le fils %d\t",getpid() );
fprintf(stdout,"J'aime mon papa %d = %d\n", getppid(), pere );
return 2;
}
return 0;
} |