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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#define SHMKEY 1234567
int mem_ID;
void* ptr_mem_partagee;
char tabNoms[80][25];
void recupNoms(void);
typedef struct coureur{
char nom[25];
int temps[3];
int cibles[1];
int penalite;
}c;
c candidat[4];
int main()
{
int parent=0, child=0, i, result=0, pid;
if ((mem_ID = shmget(SHMKEY, 5*sizeof(c), 0666 | IPC_CREAT)) < 0)
{
perror("shmget");
exit(1);
}
if ((ptr_mem_partagee = shmat(mem_ID, NULL, 0)) == (void*) -1)
{
perror("shmat");
exit(1);
}
recupNoms();
for(i=0;i<79;i++) printf("%s \n",tabNoms[i]);
pid = fork(); //crée un fils
for (i = 0; i < 5; i++)
{
switch (pid)
{
case -1:
//erreur
perror("Une erreur est survenue lors du fork()\n");
exit(99);
case 0:
//processus enfant
printf("child %d %d\n",parent, child++);
strcpy(candidat[i].nom,tabNoms[i]);
printf("candidat %d : %s \n",i+1,candidat[i].nom);
//on met Ã* jour la structure dans la memoire partagée
*((c*)ptr_mem_partagee + (i*sizeof(c))) = candidat[i];
exit(1);
default:
//processus parent
wait(NULL);
printf("parent %d %d\n", parent++, child);
pid = fork(); //on crée un nouveau processus enfant
break;
}
}
shmdt(ptr_mem_partagee);
return 0;
}
void recupNoms()
{
FILE * pFile;
int i=0;
pFile=fopen("candidats.txt","r");
if(pFile==NULL)
{
perror("fopen");
exit(1);
}
else
{
while(!feof(pFile))
{
fgets(tabNoms[i], 25, pFile);
i++;
}
fclose(pFile);
}
} |
Partager